Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading