This is a known issue with top
. As explained here, the 1st iteration of top -b
returns the percentages since boot, we therefore need at least two iterations (-n 2
) to get the current percentage. To speed things up, you can set the d
elay between iterations to 0.01
. top
splits CPU usage between user, system processes and nice
processes, we want the sum of the three. Finally, you grep
the line containing the CPU percentages and then use gawk
to sum user, system and nice processes:
top -bn 2 -d 0.01 | grep '^%Cpu' | tail -n 1 | gawk '{print $2+$4+$6}'
----- ------ ----------- --------- ----------------------
| | | | |------> add the values
| | | |--> keep only the 2nd iteration
| | |----------------> keep only the CPU use lines
| |----------------------------> set the delay between runs
|-----------------------------------> run twice in batch mode