可靠监测当前CPU使用率
我想用Python监控Mac上当前的整体CPU使用情况。
我写了一些代码,启动了'ps'命令,并把'%cpu'这一列的所有值加起来。
def psColumn(colName):
"""Get a column of ps output as a list"""
ps = subprocess.Popen(["ps", "-A", "-o", colName], stdout=subprocess.PIPE)
(stdout, stderr) = ps.communicate()
column = stdout.split("\n")[1:]
column = [token.strip() for token in column if token != '']
return column
def read(self):
values = map(float, psColumn("%cpu"))
return sum(values)
但是,我总是得到50%到80%之间的高读数,这可能是因为测量程序本身的原因。这种CPU使用峰值在我的MenuMeters或其他系统监控程序上并没有显示出来。我该如何获取更接近MenuMeters显示的读数?(我想检测一些程序是否在占用过多的CPU。)
另外,我试过psutil,但是
psutil.cpu_percent()
总是返回100%,所以要么对我没用,要么我用错了。
4 个回答
1
我几周前也在做差不多的事情,当时我也遇到了psutil.cpu_percent()的问题。
于是我改用了psutil.cpu_times(),这个方法可以告诉你CPU在用户、系统、空闲等不同状态下的使用时间,具体内容还会根据你的操作系统有所不同。我不确定这样做是否好,或者是否准确。
import psutil as ps
class cpu_percent:
'''Keep track of cpu usage.'''
def __init__(self):
self.last = ps.cpu_times()
def update(self):
'''CPU usage is specific CPU time passed divided by total CPU time passed.'''
last = self.last
current = ps.cpu_times()
total_time_passed = sum([current.__dict__.get(key, 0) - last.__dict__.get(key, 0) for key in current.attrs])
#only keeping track of system and user time
sys_time = current.system - last.system
usr_time = current.user - last.user
self.last = current
if total_time_passed > 0:
sys_percent = 100 * sys_time / total_time_passed
usr_percent = 100 * usr_time / total_time_passed
return sys_percent + usr_percent
else:
return 0
3
>>> import psutil, time
>>> print psutil.cpu_times()
softirq=50.87; iowait=39.63; system=1130.67; idle=164171.41; user=965.15; irq=7.08; nice=0.0
>>>
>>> while 1:
... print round(psutil.cpu_percent(), 1)
... time.sleep(1)
...
5.4
3.2
7.3
7.1
2.5
当然可以!请把你想要翻译的内容发给我,我会帮你用简单易懂的语言解释清楚。
3
要检测一些程序占用CPU过多的关键情况,查看负载平均值可能更好。可以试试“uptime”这个命令。
负载平均值告诉你,平均有多少个进程正在使用或等待CPU来执行。如果这个值接近或超过1.0,就意味着系统一直在忙着处理某些事情。如果负载平均值持续上升,说明系统跟不上需求,任务开始堆积。监控负载平均值而不是CPU使用率来判断系统“健康”有两个好处:
- 系统给出的负载平均值已经是经过平均计算的,不会有太大波动,所以你不用担心解析“ps”命令输出时遇到的问题。
- 有些应用可能在疯狂读写硬盘,导致系统变得无响应。在这种情况下,CPU使用率可能很低,但负载平均值仍然很高,这就说明有问题。
另外,监控一下空闲内存和交换空间也是个好主意。