2015-10-05 88 views
0

在我的java程序中,我使用Jsch連接到遠程服務器,現在我需要獲得該服務器的Cpu利用率。我已經使用iostat -c命令來獲取CPU的詳細信息...;我得到的細節如下:實時總CPU平均負載命令

Linux 3.1.0-1.2-desktop (ccitsuse06) 10/05/2015  _i686_ (4 CPU) 
avg-cpu: %user %nice %system %iowait %steal %idle 
      0.06 0.00 0.03 0.00 0.00 99.91 

我真正需要的總average CPU load;我怎樣才能得到相同的使用命令?有沒有簡單的單一命令可以實時給出總平均Cpu ......還是我需要解析這些數據的結果?再次;什麼因素有助於總平均CPU,以便我可以計算。我讀過以前的類似問題,但沒有一個能夠解決我的疑問。

*請注意,這是我需要我的程序當前/實時平均CPU負載,我希望儘可能準確執行的命令,並儘可能快..

我一直在閱讀使用awk,egrep等,但我仍然不知道如何使用這個命令來達到我想要的結果!

+1

這個問題屬於superuser.com – specializt

+0

目前還不清楚「當前/實時平均」是什麼意思。你想要現在的價值,還是最近一段時間的平均價值?彼得的答案假設後者;我認爲前者。 –

+0

謝謝......我認爲它會......而且當我逐步執行命令時,我對grep函數有了更好的理解......,並且我需要平均的CpuLoad(意味着此中所有4個內核的平均負載情況)即時;即;當前值。我認爲你的命令對我來說工作得很好....謝謝.... –

回答

0

嘗試

mpstat -u | grep -A 1 '%idle' | tail -1 | sed -r 's/ +/ /g' | cut -d' ' -f12 

如果你想了解它在做什麼,你應該嘗試執行它的點點滴滴(開始只是第一部分,然後再加上grep部分等)。

這會使用mpstat獲取所有統計數據;然後僅使用grep的相關行;使用tail擺脫標題行;使用sed壓縮額外空間;然後使用cut獲得第12列。

這會給你的空閒看書,作爲一個值超出100把它變成一個百分比數字CPU使用率,你需要減去100

0

該值以獲取平均CPU加載一段時間後,您需要查看該時間段開始和結束時使用的CPU。您可以對具有每個邏輯CPU使用時間量的/proc/stat進行採樣,或者需要運行實用程序以獲取您想要採樣的時間量。

例如

head -1 /proc/stat 

打印

cpu 170661 1384 22478 7836920 3244 0 2645 0 0 0 

從文檔,這是

cpu 3357 0 4313 1362393 
    The amount of time, measured in units of USER_HZ 
    (1/100ths of a second on most architectures, use 
    sysconf(_SC_CLK_TCK) to obtain the right value), that 
    the system spent in various states: 

    user (1) Time spent in user mode. 

    nice (2) Time spent in user mode with low priority 
      (nice). 

    system (3) Time spent in system mode. 

    idle (4) Time spent in the idle task. This value 
      should be USER_HZ times the second entry in the 
      /proc/uptime pseudo-file. 

    iowait (since Linux 2.5.41) 
      (5) Time waiting for I/O to complete. 

    irq (since Linux 2.6.0-test4) 
      (6) Time servicing interrupts. 

    softirq (since Linux 2.6.0-test4) 
      (7) Time servicing softirqs. 

    steal (since Linux 2.6.11) 
      (8) Stolen time, which is the time spent in 
      other operating systems when running in a 
      virtualized environment 

    guest (since Linux 2.6.24) 
      (9) Time spent running a virtual CPU for guest 
      operating systems under the control of the Linux 
      kernel. 

    guest_nice (since Linux 2.6.33) 
      (10) Time spent running a niced guest (virtual 
      CPU for guest operating systems under the 
      control of the Linux kernel). 

如果你採取任何兩個樣本之間這些數值的差異,你可以的時候忙的百分比。