这是一个已经被问过很多次的问题,但是我找不到得到充分支持的答案。
很多人建议使用 top 命令,但如果你运行一次 top(因为你有一个脚本,例如每 1 秒收集一次 Cpu 使用情况),它总是会给出相同的 Cpu 使用结果( 示例 1 , 示例 2 )。
计算 CPU 使用率的更准确方法是从 /proc/stat
中读取值,但大多数答案仅使用 /proc/stat
中的前 4 个字段来计算( 这里 有一个示例) .
/proc/stat/
从 Linux 内核 2.6.33 开始,每个 CPU 内核有 10 个字段!
我还发现这个 Accurately Calculating CPU Utilization in Linux using /proc/stat 问题指出了同样的问题——大多数其他问题只考虑了众多领域中的 4 个——但这里给出的答案仍然以“我think”(不确定),除此之外,它只关注前 7 个字段(在 /proc/stat/
中的 10 个字段中)
这个 perl 脚本使用所有字段来计算 CPU 使用率,经过进一步调查,我再次认为这不正确。
After taking a quick look into the kernel code here , it looks like, for example, guest_nice
and guest fields
are always increasing together with nice
and user
(因此它们不应包含在 CPU 使用率计算中,因为它们已包含在 nice
和 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使用率的准确方法是什么,计算中应该考虑哪些字段以及如何(哪些字段归因于空闲时间,哪些字段归因于非空闲时间)?
原文由 Vangelis Tasoulas 发布,翻译遵循 CC BY-SA 4.0 许可协议
根据 htop 源代码,我的假设看起来是有效的:
(参见
static inline double LinuxProcessList_scanCPUTime(LinuxProcessList* this)
中 的函数)因此,从
/proc/stat
的第一行中列出的字段中:(请参阅 文档 中的第 1.8 节)从算法上讲,我们可以计算 CPU 使用率,如下所示: