man page中給出的定義:linux
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).express
man page 定義:segmentfault
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.session
默認狀況下是3s刷新一次屏幕,也就是3s內的cpu使用狀況。app
ps是從進程啓動就開始計算,是平均的佔用率;而top是從上次刷新開始算的,通常幾秒鐘一刷,能夠認爲是即時的。並且top默認cpu的佔用率的和並非100%,而是核數x100%,因此有時會有一個進程佔用超過100%的狀況。less
top命令中的%CPU字段表示:在一個固定的間隔時間內,某個進程使用的CPU時間佔總CPU時間(即這段間隔時間)的比值。[在Window操做系統下的資源管理器中的CPU字段含義也是如此]ide
$ 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個參含義以下:操作系統
cstime=0 累計的該任務的全部的waited-for進程曾經在覈心態運行的時間,單位爲jiffies
(子進程內核態消耗的時間)unix
start_time 進程的啓動時間(相對於系統開機時刻), 單位爲jiffiescode
ps 命令中的time字段表示佔用cpu時間,
$ ps –p 1222 –otime
這個時間是如何計算的呢?
經過與/proc/pid/stat中數據的比對,能夠得出ps的cpu時間
time=utime + systime
則ps的%CPU=time/進程生命週期。
計算公式:
%CPU=cpu_time/interval
一般,進程佔用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表示1s 振動次數(滴答數)。
可以使用命令返回每秒鐘的滴答數HZ
$ getconf CLK_TCK
總滴答數除以HZ就是,就是以秒爲單位的時間
可使用開機啓動時間計算間隔:
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