这是一个已经被问过很多次的问题,但是我找不到得到充分支持的答案。
许多人建议使用 top 命令,但如果您运行 top 一次(因为您有一个脚本,例如每 1 秒收集一次 Cpu 使用情况),它将始终给出相同的 Cpu 使用结果(示例1 https://unix.stackexchange.com/questions/69185/getting-cpu-usage-same-every-time, 示例2 https://unix.stackexchange.com/questions/27076/how-can-i-receive-top-like-cpu-statistics-from-the-shell).
计算 CPU 使用率的更准确方法是读取以下值/proc/stat
,但大多数答案仅使用前 4 个字段/proc/stat
计算它(一个例子here https://unix.stackexchange.com/questions/27076/how-can-i-receive-top-like-cpu-statistics-from-the-shell).
/proc/stat/
从 Linux 内核 2.6.33 开始,每个 CPU 核心有 10 个字段!
我也发现了这个使用 /proc/stat 准确计算 Linux 中的 CPU 利用率 https://stackoverflow.com/questions/5514119/accurately-calculating-cpu-utilization-in-linux-using-proc-stat问题指出了同样的问题,-大多数其他问题只考虑众多领域中的 4 个-但这里给出的答案仍然以“我认为”(不确定)开头,除此之外,它只涉及关于前 7 个字段(共 10 个字段)/proc/stat/
)
This https://gist.github.com/creaktive/781248perl 脚本使用所有字段来计算 CPU 使用率,经过进一步调查后,我再次认为这不正确。
快速查看内核代码后here http://git.kernel.org/cgit/linux/kernel/git/torvalds/linux.git/tree/kernel/sched/cputime.c?h=v4.8#n169,例如,看起来像guest_nice
and guest fields
总是与一起增加nice
and user
(因此它们不应包含在 cpu 使用率计算中,因为它们包含在nice
and user
已经字段)
/*
* Account guest cpu time to a process.
* @p: the process that the cpu time gets accounted to
* @cputime: the cpu time spent in virtual machine since the last update
* @cputime_scaled: cputime scaled by cpu frequency
*/
static void account_guest_time(struct task_struct *p, cputime_t cputime,
cputime_t cputime_scaled)
{
u64 *cpustat = kcpustat_this_cpu->cpustat;
/* Add guest time to process. */
p->utime += cputime;
p->utimescaled += cputime_scaled;
account_group_user_time(p, cputime);
p->gtime += cputime;
/* Add guest time to cpustat. */
if (task_nice(p) > 0) {
cpustat[CPUTIME_NICE] += (__force u64) cputime;
cpustat[CPUTIME_GUEST_NICE] += (__force u64) cputime;
} else {
cpustat[CPUTIME_USER] += (__force u64) cputime;
cpustat[CPUTIME_GUEST] += (__force u64) cputime;
}
}
那么总结一下,在Linux中计算CPU使用率的准确方法是什么?在计算中应该考虑哪些字段以及如何计算(哪些字段归因于空闲时间,哪些字段归因于非空闲时间)?