可靠监控当前CPU usag

2024-04-26 01:38:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我想用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使用高峰不会在我的菜单或其他系统监视程序上注册。我怎样才能得到更像菜单显示的读数?(我想检测一些程序占用CPU的严重情况。)

我试过psutil,但是

psutil.cpu_percent()

总是100%的回报,所以要么对我没用,要么我用错了。


Tags: 程序tokenreturn系统defstdout情况column
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

对于检测某些程序占用CPU的关键情况,查看平均负载可能更好?看看“正常运行时间”命令。

Load average number告诉您平均有多少进程正在使用或等待CPU执行。如果接近或超过1.0,则表示系统一直在忙于某些事情。如果负载平均值不断提高,则意味着系统无法跟上需求,任务开始堆积。监视系统“运行状况”的平均负载而不是CPU利用率有两个优点:

  • 系统给出的负载平均值已经取平均值。它们不会有太大的波动,所以在解析“ps”输出时不会遇到这个问题。
  • 某些应用程序可能正在冲击磁盘并使系统无响应。在这种情况下,CPU利用率可能很低,但平均负载仍然很高,这表明存在问题。

同时监视空闲的RAM和swap也是一个好主意。

几周前我还在做同样的事情,我也遇到了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

相关问题 更多 >