我正在尝试使用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)
答案 0 :(得分:0)
根据文档,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)