2

If I have a cgroup like user.slice and have CPUAccounting=true set up, I'm wondering how one would calculate the CPU Usage of that particular cgroup over a period of time (such as 1s), using either cpuacct.usage or cpuacct.stat. I know cpuacct.usage provides the CPU time (in nanoseconds), which could be used to calculate the CPU percentage by subtracting two snapshots of it during a period of time and dividing it by the total CPU time of the system over the same period of time (correct me if I'm wrong), but I'm unsure how to get the total CPU time over a period of time.

Is there a way I can get the total CPU time over a period of time or use a different formula/cgroup feature to calculate the CPU Usage? Thanks in advance :)

Note: I am aware of systemd-cgtop, which provides some of this information, however I want to calculate the CPU Usage programatically without having to parse systemd-cgtop

3

CPU usage percentage is the ratio of the total time the CPU was active, to the elapsed time of the clock on your wall. If you try and compare one CPU time to another CPU time, this isn't usage percentage. There is no name for this, it's just the ratio of one CPU time to another CPU time.

You've already stated you know how to get elapsed CPU time (by taking the difference of CPU time before & after your period), so just divide that by wall clock time.

cgroup=$(awk -F: '$2 == "cpu,cpuacct" { print $3 }' /proc/self/cgroup)

tstart=$(date +%s%N)
cstart=$(cat /sys/fs/cgroup/cpu/$cgroup/cpuacct.usage)

sleep 5

tstop=$(date +%s%N)
cstop=$(cat /sys/fs/cgroup/cpu/$cgroup/cpuacct.usage)

bc -l <<EOF
($cstop - $cstart) / ($tstop - $tstart) * 100
EOF

If you want to avoid the call to date (and cat), you could use something like: read tstart _ < /proc/uptime.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.