gpt4 book ai didi

linux - 如何使用linux top命令计算CPU负载

转载 作者:太空宇宙 更新时间:2023-11-04 10:15:40 25 4
gpt4 key购买 nike

我正在运行 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com