2012-01-26 65 views
1

我需要計算的CPU使用率和在Linux的proc文件總IT獲取CPU使用率和計算%使用

的/ proc/STAT給我的數據,但如何將我才知道在時間使用的CPU%作爲 統計給我在任何時候運行的核心進程的計數,這不會給我任何%使用CPU的想法? 而我在Golang編碼,必須這樣做沒有腳本

在此先感謝!

回答

1

/proc/stat不僅會爲您提供每個核心的進程數量。 man proc會告訴你該文件的確切格式。從它複製的,這裏是你應該關心的部分:

/proc/stat 
      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 user mode, user mode with low priority 
       (nice), system mode, and the idle task, respectively. 
       The last value should be USER_HZ times the second entry 
       in the uptime pseudo-file. 

它是那麼容易做到的兩項措施,這將給你所花費的時間不受此CPU做任何事情的idle領域的減法。其他值,你可以提取是做什麼的時候,這是兩項措施之間的區別:

time in user mode + time spent in user mode with low priority + time spent in system mode 

然後,您將有兩個值;一,A表示時間無所事事,另一個B表示實際上做某事的時間。 B/(A + B)會給你CPU忙的時間百分比。