如何使用Linux TOP命令计算CPU负载



我在循环中运行top -b -n2 -d 1 | grep Cpu,并注意到它在每个迭代中返回两个条目...

1)对于每个循环,结果有两行...我应该使用第一行或第二行...两者之间有什么区别?

2)要计算CPU利用率,我是否会添加%sy,%ni,%hi和%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

我需要第二个条目...

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

最新更新