psutil: Measuring the cpu usage of a specific process

user1018517 picture user1018517 · Dec 18, 2016 · Viewed 11.8k times · Source

Im trying to measure the cpu usage of a process tree.

Currently getting the cpu_usage of a process (without children) will do, but I'm getting weird results.

import psutil
p = psutil.Process(PID)
p.cpu_percent

gives me back float>100, how is that even possible?

btw PID is the pid of something simple as

def foo():
    i = 0
    while True:
        i += 1

which according to task manager its cpu usage is around 12%

I want to get an output of 12.5 or something like that.

Answer

sergenp picture sergenp · Dec 18, 2016

I read some documentation about psutil and here is what I got:

Note: a percentage > 100 is legitimate as it can result from a process with >multiple threads running on different CPU cores.

So in order to get rid of >100 you should do something like this:

Note: the returned value is explcitly not split evenly between all CPUs cores (differently from psutil.cpu_percent()). This means that a busy loop process running on a system with 2 CPU cores will be reported as having 100% CPU utilization instead of 50%. This was done in order to be consistent with UNIX’s “top” utility and also to make it easier to identify processes hogging CPU resources (independently from the number of CPU cores). It must be noted that in the example above taskmgr.exe on Windows will report 50% usage instead. To emulate Windows’s taskmgr.exe behavior you can do:

p.cpu_percent() / psutil.cpu_count().

Since i got this answer from somewhere else, I'll give you a link to check it out: http://psutil.readthedocs.io/en/release-2.2.1/#psutil.Process.cpu_percent