简体   繁体   English

psutil.cpu_percent()函数如何工作?

[英]How psutil.cpu_percent() function works?

I was executing the below two statements in python interpreter. 我在python解释器中执行以下两个语句。

>>> psutil.cpu_percent(interval=None, percpu=False)
2.0
>>> psutil.cpu_percent(interval=None, percpu=True)
[1.5, 1.6, 3.7, 3.5]

when percpu=False it is expected to give system-wide CPU usage. 当percpu = False时,它应该提供系统范围的CPU使用率。 However, when I try to get each CPU usage, its sum doesn't equal system-wide usage.My question is how exactly cpu_percent function works when percpu=True and percpu=False is passed? 但是,当我尝试获取每个CPU的使用时,它的总和不等于系统范围的使用。我的问题是当percpu = True并且percpu = False被传递时cpu_percent函数是如何工作的?

There are two reasons you do not get what you expect to. 有两个原因导致您无法达到预期效果。

First of all, the value returned with percpu=False should be an average, not a sum of the values returned with percpu=True . 首先, percpu=False返回的值应该是平均值,而不是percpu=True返回的值的总和。 In other words, a call with percpu=False returns an average utilization for all cores/CPUs. 换句话说,使用percpu=False的调用返回所有内核/ CPU的平均利用率。 This makes sense, because if you have 4 cores, and one of them is 100% busy, but three others are idle (0% utilization) then only 25% of total CPU capacity is used. 这是有道理的,因为如果你有4个核心,其中一个是100%忙,但其他三个是空闲的(0%利用率),那么只使用总CPU容量的25%。

Second problem is when you pass interval=None you get utilization measured since the last call to cpu_percent . 第二个问题是当你传递interval=None你得到自上次调用cpu_percent以来的利用率。 Quote from the doc : 文档引用:

When interval is 0.0 or None compares system CPU times elapsed since last call or module import, returning immediately. 当interval为0.0或None时,比较自上次调用或模块导入后经过的系统CPU时间,立即返回。

So you are actually compare different measures, and obviously CPU utilization might change between these measures. 因此,您实际上是在比较不同的度量,显然CPU利用率可能在这些度量之间发生变化

From my experiments and reading the code it looks like with psutil.cpu_percent and percpu=False , 100% means that all cores are used 100%. 从我的实验和读取代码看起来像psutil.cpu_percentpercpu=False ,100%表示所有核心都是100%使用。 The code comments describe this as the "Windows Task Manager style". 代码注释将其描述为“Windows任务管理器样式”。 This is roughly equivalent to taking the average CPU utilization per core. 这大致相当于获取每个核心的平均CPU利用率。 Instead you might be used to the unix style, which just sums the per-core utilization, so the maximum would be eg 400% for your 4-core machine. 相反,您可能会习惯使用unix样式,它只是对每个核心的利用率求和,因此对于4核机器,最大值为400%。

Interestingly, psuitl.Process.cpu_percent calculates the unix-style utilization instead. 有趣的是, psuitl.Process.cpu_percent计算unix样式的利用率。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM