简体   繁体   English

如何测量python中进程的平均CPU使用率

[英]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.

相关问题 如何测量 Python 中单个代码行的 CPU 使用率(百分比)? - How to measure cpu usage (as a percentage) of a single code line in Python? 测量 python 中 tesorflow 的 cpu 使用/执行时间 - Measure the cpu usage/execution time for tesorflow in python Python中每个进程的CPU使用率 - CPU Usage Per Process in Python 如何使用 python 获得准确的进程 CPU 和 memory 使用情况? - How to get accurate process CPU and memory usage with python? 如何测量给定时刻的进程内存使用情况 - How to measure process memory usage in given moment 获取 python 中的进程 CPU 使用率百分比 - Get process CPU usage in percentage in python 如何使用 python 检查我的 CPU 使用率、堆使用率、线程数、进程数? - How to check my CPU usage, heap usage, thread count, process count using python? 如何通过python获取GCP实例每天的平均CPU使用率? - how to get the average CPU usage of GCP instance per day via python? 为什么我的 Python 程序平均每个进程只占用 33% 的 CPU? 如何让 Python 使用所有可用的 CPU? - Why does my Python program average only 33% CPU per process? How can I make Python use all available CPU? 如何分析Python脚本的CPU使用情况? - How to profile CPU usage of a Python script?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM