Search code examples
javaamazon-web-servicesdockerdevopsamazon-ecs

Calculate CPU percentage of a docker container based on CPUSTATS and PRECPUSTATS returned from ECS task metadata endpoint


I was trying to calculate the CPU percentage of docker container that was currently up and running.

A call was made to ECS task metadata endpoint that returns a JSON file was Response which contains CPUSTATS, PRECPUSTATS, online_cpus, system_cpu_usage etc...

The formula that I usually using was as follows to calculate CPU percentages

Average cpu usage=((cpu_stats.total_usage - precpu_stats.total_usage) / (number of online cpu) )* 100.

And Dividng the Average cpu usage by difference between the read and preread timestamps as follows.

CPU PERCENTAGE= Average cpu usage/(read-preread).

But from the above calculation the percentage was not accurate it was returing me a wrong value.

When checked the CPU usage in the host machine using ""docker stats" command it was showing correct results.

Is this correct way of calculating cpu percentages?

thanks,


Solution

  • I am currently working on container level metrics for aws ecs and came across this link which explains how to calculate CPU usage in percentage from the ecs metadata ECS-calculate-CPU-utilization-metadata-endpoint

    This is the gist basically:

    1. cpu_delta = cpu_stats.cpu_usage.total_usage - precpu_stats.cpu_usage.total_usage
    2. system_cpu_delta = cpu_stats.system_cpu_usage - precpu_stats.system_cpu_usage
    3. number_cpus = length(cpu_stats.cpu_usage.percpu_usage) or cpu_stats.online_cpus

    Finally:

    CPU usage % = (cpu_delta / system_cpu_delta) * number_cpus * 100.0

    I am going to implement this right now. This will give the increase or decrease in cpu usage from last sampling time.