psutil:测量特定进程的 cpu 使用情况
psutil: Measuring the cpu usage of a specific process
我正在尝试测量进程树的 cpu 使用率。
目前获取进程(没有子进程)的 cpu_usage 就可以了,但我得到了奇怪的结果。
import psutil
p = psutil.Process(PID)
p.cpu_percent
还我float
>100
,这怎么可能?
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().
因为我从别处得到这个答案,我会给你一个link来检查它
输出:http://psutil.readthedocs.io/en/release-2.2.1/#psutil.Process.cpu_percent
我正在尝试测量进程树的 cpu 使用率。
目前获取进程(没有子进程)的 cpu_usage 就可以了,但我得到了奇怪的结果。
import psutil
p = psutil.Process(PID)
p.cpu_percent
还我float
>100
,这怎么可能?
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().
因为我从别处得到这个答案,我会给你一个link来检查它 输出:http://psutil.readthedocs.io/en/release-2.2.1/#psutil.Process.cpu_percent