简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM