【发布时间】:2014-06-15 13:54:39
【问题描述】:
这是一个被问过很多次的问题,但是我找不到得到充分支持的答案。
很多人建议使用 top 命令,但是如果你运行一次 top(因为你有一个脚本,例如每 1 秒收集一次 Cpu 使用情况)它总是会给出相同的 Cpu 使用结果(example 1,example 2 )。
一种更准确的计算 CPU 使用率的方法是读取来自 /proc/stat 的值,但大多数答案仅使用来自 /proc/stat 的前 4 个字段来计算它(一个示例 here)。
/proc/stat/ 自 Linux 内核 2.6.33 起每个 CPU 内核有 10 个字段!
我还发现了这个Accurately Calculating CPU Utilization in Linux using /proc/stat 问题,它指出了同样的问题——大多数其他问题只考虑了众多领域中的 4 个——但这里给出的答案仍然以“我认为”开头(不确定),除此之外,它只关注前 7 个字段(/proc/stat/ 中的 10 个字段)
This perl 脚本使用所有字段来计算 CPU 使用率,经过进一步调查,我认为这也是不正确的。
在快速查看内核代码here 后,看起来,例如,guest_nice 和 guest fields 总是与 nice 和 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使用率的准确方法是什么,计算中应该考虑哪些字段以及如何(哪些字段归因于空闲时间,哪些字段归因于非空闲时间)?
【问题讨论】:
-
每秒收集CPU使用信息的正确方法是连续运行
top -b。 -
我想使用第 3 方脚本收集数据,而 CPU 只是需要收集的指标之一。因此,我想计算自上次运行此第 3 方脚本以来的 CPU 使用率(时间间隔可能会有所不同)。
top -b连续运行,所以它必须在单独的线程中运行,并将收集到的数据保存在不同的输出中。 -
正在寻找什么 CPU 使用率?一个进程?全系统?是否应该用百分比、秒、...来表示?
-
上次测量的使用百分比!
标签: linux linux-kernel cpu calculator cpu-usage