gpt4 book ai didi

python - psutil:测量特定进程的cpu使用率

转载 作者:太空狗 更新时间:2023-10-30 02:08:44 31 4
gpt4 key购买 nike

我正在尝试测量进程树的 CPU 使用率。

目前获取一个进程(没有子进程)的 cpu_usage 就可以了,但是我得到了奇怪的结果。

import psutil
p = psutil.Process(PID)
p.cpu_percent

返回float100,这怎么可能?

btw PID 是一些简单的东西的 pid

def foo():
i = 0
while True:
i += 1

根据任务管理器,它的 CPU 使用率约为 12%

我想得到 12.5 或类似的输出。

最佳答案

我阅读了一些关于 psutil 的文档,这是我得到的:

Note: a percentage > 100 is legitimate as it can result from a process with >multiple threads running on different CPU cores.

所以为了摆脱 >100 你应该这样做:

Note: the returned value is explcitly not split evenly between all CPUs cores (differently from psutil.cpu_percent()). This means that a busy loop process running on a system with 2 CPU cores will be reported as having 100% CPU utilization instead of 50%. This was done in order to be consistent with UNIX’s “top” utility and also to make it easier to identify processes hogging CPU resources (independently from the number of CPU cores). It must be noted that in the example above taskmgr.exe on Windows will report 50% usage instead. To emulate Windows’s taskmgr.exe behavior you can do:

p.cpu_percent() / psutil.cpu_count().

由于我从其他地方得到了这个答案,我会给你一个链接来检查它输出:http://psutil.readthedocs.io/en/release-2.2.1/#psutil.Process.cpu_percent

关于python - psutil:测量特定进程的cpu使用率,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41206809/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com