Get Docker Container CPU Usage as Percentage

前端 未结 3 1657
伪装坚强ぢ
伪装坚强ぢ 2020-12-14 17:10

Docker provides an interactive stats command, docker stats [cid] which gives up to date information on the CPU usage, like so:

CONTAINER      CPU         


        
相关标签:
3条回答
  • 2020-12-14 17:20

    After we consume the remote api we get these fields: precpu_stats/cpu_stats

    Then, basically here is the code: (javascript example)

    var res <---- remote api response
    
    var cpuDelta = res.cpu_stats.cpu_usage.total_usage -  res.precpu_stats.cpu_usage.total_usage;
    var systemDelta = res.cpu_stats.system_cpu_usage - res.precpu_stats.system_cpu_usage;
    var RESULT_CPU_USAGE = cpuDelta / systemDelta * 100;
    

    Just to clarify the RESULT_CPU_USAGE... it's the amount of resource consumed from your physical hardware, so supposing you are getting RESULT_CPU_USAGE as 50%, it means that 50% of all your PC power is being used by container X

    0 讨论(0)
  • 2020-12-14 17:34

    If you are going to use the Stats API call - you can take a look at how the docker client does it: https://github.com/docker/docker/blob/eb131c5383db8cac633919f82abad86c99bffbe5/cli/command/container/stats_helpers.go#L175-L188

    func calculateCPUPercent(previousCPU, previousSystem uint64, v *types.StatsJSON) float64 {
        var (
            cpuPercent = 0.0
            // calculate the change for the cpu usage of the container in between readings
            cpuDelta = float64(v.CPUStats.CPUUsage.TotalUsage) - float64(previousCPU)
            // calculate the change for the entire system between readings
            systemDelta = float64(v.CPUStats.SystemUsage) - float64(previousSystem)
        )
    
        if systemDelta > 0.0 && cpuDelta > 0.0 {
            cpuPercent = (cpuDelta / systemDelta) * float64(len(v.CPUStats.CPUUsage.PercpuUsage)) * 100.0
        }
        return cpuPercent
    }
    

    Basically, you take a point of reference, then see the difference in say 10 secs, you can then tell how much of the time was used by the container. Say, we start with 0 SystemCPUUsage and 0 CPUUsage for the container. If after 10 secs, we have 10 SystemCPUUsage and 1 CPUUsage, then we have 10% usage. You are just given the results in nanoseconds, not seconds, in the API. The actual time does not matter, the total SystemCPUUsage change is what matters, then compare CPUUSage to that.

    0 讨论(0)
  • 2020-12-14 17:43

    So I need this also, and the following gives me the correct CPU usage, factoring in number of cores.

    var cpuDelta = metric.cpu_stats.cpu_usage.total_usage -  metric.precpu_stats.cpu_usage.total_usage;
    var systemDelta = metric.cpu_stats.system_cpu_usage - metric.precpu_stats.system_cpu_usage;
    var RESULT_CPU_USAGE = cpuDelta / systemDelta * metric.cpu_stats.cpu_usage.percpu_usage.length * 100;
    
    console.log(RESULT_CPU_USAGE);
    
    0 讨论(0)
提交回复
热议问题