[英]psutil's proc.as_dict attribute “get_cpu_percent” returns 0.0 for each process
I am trying to write a very simple python script using the psutil module to return process ID, Create time, Name and CPU %. 我正在尝试使用psutil模块编写一个非常简单的python脚本,以返回进程ID,创建时间,名称和CPU%。 Ultimately I will use this to monitor specific thresholds based on these returned values, but for our case, I'll use a simple example
最终,我将使用它来基于这些返回值监视特定的阈值,但是对于我们的情况,我将使用一个简单的示例
When I run the following script, it returns the correct values for everything but cpu_percent. 当我运行以下脚本时,它将为除cpu_percent之外的所有内容返回正确的值。 It returns 0.0 for each process.
每个进程返回0.0。 I think the problem is due to the default interval being 0 for cpu_percent.
我认为问题是由于cpu_percent的默认间隔为0。 I'm using psutil.process_iter() and as_dict to iterate through the running processes.
我正在使用psutil.process_iter()和as_dict遍历正在运行的进程。 I'm not sure how I would set the interval.
我不确定如何设置间隔。 Is there something I'm missing?
有什么我想念的吗?
#! /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)
According to the docs, get_cpu_percent
will allow you to measure the amount of CPU time a particular process is using as a blocking measurement. 根据文档,
get_cpu_percent
将允许您测量特定进程用作阻塞度量的CPU时间。 For example: 例如:
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()
Instead, you probably want to use get_cpu_times
in your report. 相反,您可能想在报表中使用
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.