How to get overall CPU usage (e.g. 57%) on Linux

user1199739 picture user1199739 · Feb 10, 2012 · Viewed 431.7k times · Source

I am wondering how you can get the system CPU usage and present it in percent using bash, for example.

Sample output:

57%

In case there is more than one core, it would be nice if an average percentage could be calculated.

Answer

vimdude picture vimdude · Feb 10, 2012

Take a look at cat /proc/stat

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

EDIT please read comments before copy-paste this or using this for any serious work. This was not tested nor used, it's an idea for people who do not want to install a utility or for something that works in any distribution. Some people think you can "apt-get install" anything.

NOTE: this is not the current CPU usage, but the overall CPU usage in all the cores since the system bootup. This could be very different from the current CPU usage. To get the current value top (or similar tool) must be used.

Current CPU usage can be potentially calculated with:

awk '{u=$2+$4; t=$2+$4+$5; if (NR==1){u1=u; t1=t;} else print ($2+$4-u1) * 100 / (t-t1) "%"; }' \
<(grep 'cpu ' /proc/stat) <(sleep 1;grep 'cpu ' /proc/stat)