Overview
For a little project I worked on I needed to get the CPU utilization as a percentage.
I Google'd the issue and searched for "cpu utilization bash".
To my surprise there were no elegant solutions. Most just failed to work (on my machine anyway) while others were very inaccurate. For example, some would show the same number over and over again. Some would change the numbers but were not related to CPU utilization at all. Others would sample the CPU utilization over 1 second which is a good idea but wouldn't work well in my script in my particular case (as my script needed an instant result).
Solution
So I came up with the following instant and accurate solution:
echo print `top -n 1 | tr -s " " | cut -d$" " -f10 | tail -n +8 | head -n -1 | paste -sd+ | bc`/ `nproc` | python
This outputs a floating point number between 0.0 and 100.0.
Essentially, we look at the current output of the top using top -n 1
and then tally up all the numbers for all processes in the CPU usage column. Then we simply divide this number by nproc
(number of processor units available) to get the overall CPU utilization. In this case python handled the floating point division for us (as bash cannot do floating point arithmetic).
Pro tip
You can use the stress
command (http://linux.die.net/man/1/stress) to stress test your system in order to check the above solution. You should notice that the script will output a number close to 100 if you stress all processor cores.