这是一个多次被问过的问题,但是我找不到很好的支持答案 .
很多人建议使用top命令,但如果你运行top一次(因为你有一个脚本,例如每1秒收集一次Cpu使用),它将始终给出相同的Cpu使用结果(example 1,example 2) .
计算CPU使用率的更准确方法是通过读取 /proc/stat
中的值,但大多数答案仅使用 /proc/stat
中的前4个字段来计算它(一个示例here) .
从Linux内核2.6.33开始, /proc/stat/
每个CPU核心有10个字段!
我也发现这个Accurately Calculating CPU Utilization in Linux using /proc/stat问题指出了同样的问题 - 大多数其他问题只考虑了很多领域中的4个 - 但这里给出的答案仍然是"I think"(不确定),除此之外,它是只关注前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使用率的准确方法,以及在计算中应考虑哪些字段以及如何(哪些字段归因于空闲时间以及哪些字段归因于非空闲时间)?
4 回答
根据撰写本文时的htop源代码,我的假设看起来有效:
(见
void ProcessList_scan(ProcessList* this)
函数ProcessList.c)因此,从
/proc/stat
第一行中列出的字段:(参见第1.1节documentation)从算法上讲,我们可以计算CPU使用百分比,如:
以下是基于Vangelis答案的bash脚本 . 它产生如下输出:
创建一个名为
get_cpu_usage.sh
的文件使用以下命令运行它:
bash get_cpu_usage.sh 0.2
参数是要测量的秒数 . 在这种情况下,它是200毫秒 .
内容如下:
嘿,我也在研究这个主题,发现这个主题非常有用 . 我使用Vangelis Tasoulas公式为此编写一个小的python脚本 . 附件是我的问题的Python代码 . 它每秒加载每个cpu_id的cpu使用量 . 也许它也有助于其他人 . 欢迎提出意见/建议:-)
idnt.net对如何使用/ proc / stat cpu数据有很好的描述,包括用于提取cpu的bash脚本和行的描述 . 我只是想在这里链接它,因为我发现它很有 Value .