歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> SHELL編程 >> Linux Shell中PS命令中的%CPU的含義介紹

Linux Shell中PS命令中的%CPU的含義介紹

日期:2017/3/2 16:52:58   编辑:SHELL編程

PS命令中的%CPU是指一個進程占用CPU的時間百分比,那麼具體的含義是什麼呢?

  PS的man手冊的解釋是這樣的:

   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).


  ps的代碼中是這樣處理的

   static int pr_pcpu(char *restrict const outbuf, const proc_t *restrict const pp){
unsigned long long total_time; /* jiffies used by this process */
unsigned pcpu = 0; /* scaled %cpu, 999 means 99.9% */
unsigned long long seconds; /* seconds of process life */
total_time = pp->utime + pp->stime;
if(include_dead_children) total_time += (pp->cutime + pp->cstime);
seconds = seconds_since_boot - pp->start_time / Hertz;
if(seconds) pcpu = (total_time * 1000ULL / Hertz) / seconds;
if (pcpu > 999U)
return snprintf(outbuf, COLWID, "%u", pcpu/10U);
return snprintf(outbuf, COLWID, "%u.%u", pcpu/10U, pcpu%10U);
}


  其中seconds_since_boot是用當前時間減去系統啟動時的時間得到的,啟動的時間通過讀/proc/stat中的btime獲得。而start_time是進程被fork時設置的。另外進程的時間包括在用戶態運行的時間和內核態運行的時間。這樣,這個百分比的含義就是從進程被創建到執行ps操作這段時間T內,這個進程運行的時間和T的比值。

  如果在ps中指定了include_dead_children選項,那麼這個進程的時間還包括它的它創建的但已經死去的進程的運行時間,cutime和cstime會在父進程為子進程收屍的時候調用wait_task_zombie來累加。比如在bash中執行updatedb,在執行完成後,運行

  ps -eo pcpu,comm,stat,pid|grep bash

  和

  ps S -eo pcpu,comm,stat,pid|grep bash

  後者的百分比更在。

Copyright © Linux教程網 All Rights Reserved