LinuxShell中PS命令中的%CPU的含義介紹

字號:

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是用當(dāng)前時間減去系統(tǒng)啟動時的時間得到的,加入收藏 啟動的時間通過讀/proc/stat中的btime獲得。而start_time是進程被fork時設(shè)置的。另外進程的時間包括在用戶態(tài)運行的時間和內(nèi)核態(tài)運行的時間。這樣,這個百分比的含義就是從進程被創(chuàng)建到執(zhí)行ps操作這段時間T內(nèi),這個進程運行的時間和T的比值。
    如果在ps中指定了include_dead_children選項,那么這個進程的時間還包括它的它創(chuàng)建的但已經(jīng)死去的進程的運行時間,cutime和cstime會在父進程為子進程收尸的時候調(diào)用wait_task_zombie來累加。比如在bash中執(zhí)行updatedb,在執(zhí)行完成后,運行
    ps -eo pcpu,comm,stat,pid|grep bash
    和
    ps S -eo pcpu,comm,stat,pid|grep bash
    后者的百分比更在。