psutil: Measuring the cpu usage of a specific process
Asked Answered
I

1

8

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.

Infinity answered 18/12, 2016 at 8:52 Comment(0)
A
15

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

Aplite answered 18/12, 2016 at 9:4 Comment(1)
Does this method still work on Intel's new chips which have both efficiency cores and performance cores? If it does work, is the value still meaningful?Merkel

© 2022 - 2024 — McMap. All rights reserved.