5

I was executing the below two statements in python interpreter.

>>> 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. 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?

user2076561
  • 139
  • 1
  • 2
  • 7

2 Answers2

4

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. In other words, a call with percpu=False returns an average utilization for all cores/CPUs. 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.

Second problem is when you pass interval=None you get utilization measured since the last call to 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.

So you are actually compare different measures, and obviously CPU utilization might change between these measures.

dvk
  • 1,420
  • 10
  • 13
1

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%. The code comments describe this as the "Windows Task Manager style". This is roughly equivalent to taking the average CPU utilization per core. Instead you might be used to the unix style, which just sums the per-core utilization, so the maximum would be e.g. 400% for your 4-core machine.

Interestingly, psuitl.Process.cpu_percent calculates the unix-style utilization instead.

Azsgy
  • 3,139
  • 2
  • 29
  • 40