Reputation: 7493
I am running top -b -n2 -d 1 | grep Cpu
in a loop and notice it returns two entries in each iteration...
1) For each loop there are two lines of results...should I be using the first or second line...what is the difference between the two?
2) To calculate the CPU utilization do I add %us, %sy, %ni, %hi and %si?
Cpu(s): 1.6%us, 1.7%sy, 0.0%ni, 96.6%id, 0.0%wa, 0.0%hi, 0.1%si, 0.0%st
Cpu(s): 8.7%us, 9.4%sy, 0.0%ni, 81.9%id, 0.0%wa, 0.0%hi, 0.0%si, 0.0%st
Cpu(s): 1.6%us, 1.7%sy, 0.0%ni, 96.6%id, 0.0%wa, 0.0%hi, 0.1%si, 0.0%st
Cpu(s): 9.7%us, 8.9%sy, 0.0%ni, 81.5%id, 0.0%wa, 0.0%hi, 0.0%si, 0.0%st
Upvotes: 0
Views: 1024
Reputation: 7493
I needed the 2nd entry...
command = "top -bn 2 -d 0.01 | grep '^Cpu' | tail -n 1 | gawk '{print $2+$4+$6}'"
The 1st iteration of top -b returns the percentages since boot,
We need at least two iterations (-n 2) to get the current percentage.
To speed things up, you can set the delay 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
Upvotes: 2