我在循环中运行top -b -n2 -d 1 | grep Cpu,注意到它在每次迭代中返回两个条目。。。
1)对于每个循环,有两行结果……我应该使用第一行还是第二行……这两行的区别是什么?
2)要计算CPU利用率,是否添加%us、%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

关于linux - 如何使用linux top命令计算CPU负载,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/46369617/

10-11 22:39
查看更多