Search code examples
pythoncpu

How to measure the average CPU usage by a process in python


I want to measure the average CPU usage of a process in python. With psutil I can only get the CPU consumption at a given time.

What I decided to do is this:


import psutil
import time

start = time.time()
end = time.time()

samples = []

while end - start < 2:
    for proc in psutil.process_iter():
        if proc.name() == "myprocess":
            samples.append(proc.cpu_percent())
            break
    end = time.time()

print("Average: " + str(sum(samples)/len(samples)))

However the results are not accurate because sometimes my process is sleeping (not using the CPU) so I get a lot of 0 in the samples list.

Isn't there a built-in function that lets me measure the CPU average consumption of my process


Solution

  • Let's say you found your process name and process ID you can call cpu_percent(interval=1)) function and pass the interval for how long you want to monitor that process here 1 = 1sec

    import psutil
    
    #PID=3124320
    #to get pid use os.getpid()
    my_process = psutil.Process(3124320)
    
    print("CPU%:", my_process.cpu_percent(interval=1))
    #CPU%: 11.0