2017-09-22 114 views
0

我運行在一個循環top -b -n2 -d 1 | grep Cpu並注意它返回每個迭代兩個條目來計算CPU負載...如何使用Linux的top命令

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 
+0

如果你沒有在這裏得到一個答案,你也可以嘗試張貼到https://unix.stackexchange.com/ – Jeremy

+0

你' - n2'這意味着兩次迭代...你想要哪種迭代?也許只是'top -b -n1 -d 1 |因爲你已經在一個循環中運行了,所以grep Cpu只需要一次迭代。 – JNevill

+0

如果我只是做-d1,那麼它似乎總是1.6%... –

回答

0

我所需要的第二項...

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