Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does cpu load not change more than a few hundredths?

Tags:

bash

cpu

cpu-load

I'm running this command

grep 'cpu ' /proc/stat | awk '{usage=($2+$4)*100/($2+$4+$5)} END {print usage "%"}'

Yet it only outputs something like 0.99xxxx%

If I do an apt-get upgrade or any process, I would imagine it would go above 1%. Even running stress -c 1 doesn't make it change any.

Is there a way to log CPU usage accurately? Server has 1 vCPU.

Need to have this log every 5 seconds.

while sleep 5; do "code" >> logfile; done
like image 517
user1052448 Avatar asked Mar 15 '23 01:03

user1052448


1 Answers

Why does cpu load not change more than a few hundredths?

Because /proc/stat is returning aggregated CPU load statistics since the system last booted, not real-time ones. If you run your script just after a reboot, the reported load might significantly change as long as the CPU load itself changes. However, the longer the script runs the lesser load changes will impact the displayed value and after a while, the value will essentially stay constant.

If you want to compute the load from /proc/stat and not use the already available tools that do it, you need to compute the difference from two consecutive samples, eg :

while sleep 5; do grep -w cpu /proc/stat ; done | \
    awk '{
        print (o2+o4-$2-$4)*100/(o2+o4+o5-$2-$4-$5) "%"
        o2=$2;o4=$4;o5=$5}'

Otherwise, a simpler but less accurate way might be:

vmstat -n 5 | \
    awk '{used=$13+$14;total=used+$15
          if(total>0) print used*100/total "%"}'
like image 153
jlliagre Avatar answered Mar 23 '23 22:03

jlliagre