[英]psutil's proc.as_dict attribute “get_cpu_percent” returns 0.0 for each process
我正在尝试使用psutil模块编写一个非常简单的python脚本,以返回进程ID,创建时间,名称和CPU%。 最终,我将使用它来基于这些返回值监视特定的阈值,但是对于我们的情况,我将使用一个简单的示例
当我运行以下脚本时,它将为除cpu_percent之外的所有内容返回正确的值。 每个进程返回0.0。 我认为问题是由于cpu_percent的默认间隔为0。 我正在使用psutil.process_iter()和as_dict遍历正在运行的进程。 我不确定如何设置间隔。 有什么我想念的吗?
#! /usr/bin/python
import psutil
for proc in psutil.process_iter():
try:
pinfo = proc.as_dict(attrs=['pid', 'name', 'create_time', 'get_cpu_percent'])
except psutil.NoSuchProcess:
pass
else:
print(pinfo)
根据文档, get_cpu_percent
将允许您测量特定进程用作阻塞度量的CPU时间。 例如:
import psutil
import os
# Measure the active process in a blocking method,
# blocks for 1 second to measure the CPU usage of the process
print psutil.Process(os.getpid()).get_cpu_percent(interval=1)
# Measure the percentage of change since the last blocking measurement.
print psutil.Process(os.getpid()).get_cpu_percent()
相反,您可能想在报表中使用get_cpu_times
。
>>> help(proc.get_cpu_times)
Help on method get_cpu_times in module psutil:
get_cpu_times(self) method of psutil.Process instance
Return a tuple whose values are process CPU user and system
times. The same as os.times() but per-process.
>>> pinfo = psutil.Process(os.getpid()).as_dict(attrs=['pid', 'name', 'create_time', 'get_cpu_times'])
>>> print (pinfo.get('cpu_times').user, pinfo.get('cpu_times').system)
(0.155494768, 0.179424288)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.