Search code examples
pythonsubprocesscpu-usagepsutil

CPU percent of running process


I'm trying to get the percent of CPU usage for an external process in python. I've seen some other posts on this topic, but haven't helped me too much. When I run the following function I get values that aren't consistent with what I'm seeing in task manager. For example, if I'm monitoring a chrome process I get values that oscillate between 1 and 2, but task manager shows values oscillating between 25 and 30. Any suggestions? Thanks.

def monitor(pid):
    cpu_table = []
    p = psutil.Process(pid)
    while p.is_running():
        cpu_table.append(p.get_cpu_percent())
        time.sleep(1)
    return cpu_table

Solution

    1. There are several chrome processes and you might be monitoring the wrong one
    2. cpu_percent() "compares system CPU times elapsed since last call or module import". Pass the same interval that task manager uses (in case, it is not 1 second). Make sure to start both your monitor() function and the task manager at the same time.