Get Docker Container CPU Usage as Percentage Get Docker Container CPU Usage as Percentage docker docker

Get Docker Container CPU Usage as Percentage


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.


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 responsevar 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


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);