[英]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.我想测量python中一个进程的平均CPU使用率。 With
psutil
I can only get the CPU consumption at a given time.使用
psutil
我只能在给定时间获得 CPU 消耗。
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.但是结果不准确,因为有时我的进程正在休眠(不使用 CPU),所以我在
samples
列表中得到了很多0
。
Isn't there a built-in function that lets me measure the CPU average consumption of my process是不是有一个内置函数可以让我测量我的进程的 CPU 平均消耗
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假设您找到了您的进程名称和进程 ID,您可以调用cpu_percent(interval=1))函数并传递您想要在此处监视该进程的时间间隔 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.