cpu的計算
ps cpu的定義
man page中給出的定義:
cpu utilization of the process in "##.#" format. Currently, it is the CPU time used divided by the time the process has been running (cputime/realtime ratio), expressed as a percentage. It will not add up to 100% unless you are lucky. (alias pcpu).
- cputime:進程生命周期中使用cpu的時間
- realtime:進程生命周期
- %cpu = cputime/realtime*100, 不可能達到100%
top cpu的定義
man page 定義:
The task's share of the elapsed CPU time since the last screen update, expressed as a percentage of total CPU time. In a true SMP environment, if 'Irix mode' is Off, top will operate in 'Solaris mode' where a task's cpu usage will be divided by the total number of CPUs. You toggle 'Irix/Solaris' modes with the 'I' interactive command.
默認情況下是3s刷新一次屏幕,也就是3s內的cpu使用情況。
ps是從進程啟動就開始計算,是平均的占用率;而top是從上次刷新開始算的,一般幾秒鍾一刷,可以認為是即時的。而且top默認cpu的占用率的和並不是100%,而是核數x100%,所以有時會有一個進程占用超過100%的情況。
top命令中的%CPU字段表示:在一個固定的間隔時間內,某個進程使用的CPU時間占總CPU時間(即這段間隔時間)的比值。[在Window操作系統下的資源管理器中的CPU字段含義也是如此]
手動計算top命令中的%CPU字段
- 利用ps
確定一個間隔時間,在間隔時間的開始處,執行ps命令,獲取某個進程在開始處已經使用的CPU時間;在間隔時間的結束處,執行ps命令,獲取某個進程在結束處已經使用的CPU時間。
間隔時間內進程使用的CPU時間=結束處使用的CPU時間-開始處使用的CPU時間
%CPU=間隔時間內進程使用的CPU時間*100/CPU總時間(即間隔時間長度) - 利用/proc下的數據
ps命令的數據來自於/proc目錄下的文件,因而如果直接使用/proc下的數據也是可以實現“手動計算top命令中的%CPU字段”的目標的
進程proc參數定義
$ cat /proc/28433/stat
28433
(happy-agent)
S
1 ppid
28395 pgrp
28395 session
0 tty
-1 tpgid
4202496
80653
91801047
0
0
96 utime
94 ctime
2932 uctime
4477 sctime
20
0
10
0
2219421267 start time
181817344 1887 18446744073709551615 1 1 0 0 0 0 0 3 2143420156 18446744073709551615 0 0 17 31 0 0 0
0
0
其中,第14,15,16.17, 21個參含義如下:
-
utime=1587 該任務在用戶態運行的時間,單位為jiffies
-
stime=1 該任務在核心態運行的時間,單位為jiffies
-
cutime=0 累計的該任務的所有的waited-for進程曾經在用戶態運行的時間,單位為jiffies
(子進程用戶態消耗的時間) -
cstime=0 累計的該任務的所有的waited-for進程曾經在核心態運行的時間,單位為jiffies
(子進程內核態消耗的時間) -
start_time 進程的啟動時間(相對於系統開機時刻), 單位為jiffies
ps 命令中的time字段表示占用cpu時間,
$ ps –p 1222 –otime
這個時間是如何計算的呢?
通過與/proc/pid/stat中數據的比對,可以得出ps的cpu時間
time=utime + systime
則ps的%CPU=time/進程生命周期。
使用proc數據計算進程CPU百分比
計算公式:
%CPU=cpu_time/interval
cpu_time的計算
通常,進程占用cpu時間cpu_time有兩種方式:
一種方式:
utime+stime+uctime+sctime
這個4個參數可以通過如下方式得到:
$ cat /proc/28433/stat | cut -d" " -f 14,15,16,17
498 402 12752 19498
即
cpu_time = (utime+stime+uctime+sctime)/HZ
另一種方式
只考慮進程自身的使用時間,不考慮子進程的使用時間。
utime+stime
即
cpu_time = (utime+stime)/HZ
HZ的計算
HZ表示1s 振動次數(滴答數)。
可使用命令返回每秒鍾的滴答數HZ
$ getconf CLK_TCK
總滴答數除以HZ就是,就是以秒為單位的時間
時間間隔interval的計算
可以使用開機啟動時間計算間隔:
interval = uptime1 – uptime2
而系統啟動時間,單位就是秒
$ cat /proc/uptime | cut -d" " -f 1
22289498.57
參考
/proc/pid/stat各字段含義
https://www.linuxidc.com/Linux/2010-12/30589.htm
如何獲取進程已經運行的時間
http://smilejay.com/2012/05/get_process_time/
ps 和top命令的cpu
https://unix.stackexchange.com/questions/58539/top-and-ps-not-showing-the-same-cpu-result