macos 可靠地监控当前的 CPU 使用率

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2311301/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 06:46:45  来源:igfitidea点击:

Reliably monitor current CPU usage

pythonmacoscpu

提问by D-Bug

I'd like to monitor the current system-wide CPU usage on a Mac with Python.

我想使用 Python 在 Mac 上监控当前系统范围的 CPU 使用率。

I've written some code that starts 'ps', and adds up all the values from the '%cpu' column.

我编写了一些以“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)

However, I always get high readings from 50% - 80%, probably caused by the measuring program itself. This CPU usage peak does not register on my MenuMeters or other system monitoring programs. How can I get readings which are more like what MenuMeters would display? (I want to detect critical situations in which some program is hogging the CPU.)

然而,我总是得到 50% - 80% 的高读数,这可能是由测量程序本身造成的。这个 CPU 使用高峰没有记录在我的 MenuMeters 或其他系统监控程序上。我怎样才能获得更像 MenuMeters 显示的读数?(我想检测某些程序占用 CPU 的危急情况。)

p.s. I have tried psutil, but

ps 我试过psutil,但是

psutil.cpu_percent()

always returns 100%, so either it's useless for me or I am using it wrongly.

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

采纳答案by Pēteris Caune

For detecting critical situations when some program is hogging the CPU perhaps looking at load average is better? Take a look at "uptime" command.

为了检测某些程序占用 CPU 时的危急情况,也许查看平均负载会更好?看看“正常运行时间”命令。

Load average number tells you how many processes on average are using or waiting on CPU for execution. If it is close to or over 1.0, it means the system is constantly busy with something. If load average is constantly raising, it means that system cannot keep up with the demand and tasks start to pile up. Monitoring load average instead of CPU utilization for system "health" has two advantages:

平均负载数告诉您平均有多少进程正在使用或等待 CPU 执行。如果它接近或超过 1.0,则表示系统一直在忙于某事。如果平均负载不断升高,则意味着系统跟不上需求,任务开始堆积。监控系统“健康”的平均负载而不是 CPU 利用率有两个优点:

  • Load averages given by system are already averaged. They don't fluctuate that much so you don't get that problem with parsing "ps" output.
  • Some app may be thrashing disk and rendering system unresponsive. In this case CPU utilization might be low, but load average would still be high indicating a problem.
  • 系统给出的平均负载已经平均。它们的波动不大,因此您在解析“ps”输出时不会遇到这个问题。
  • 某些应用程序可能会抖动磁盘并使系统无响应。在这种情况下,CPU 利用率可能较低,但平均负载仍然很高,表明存在问题。

Also monitoring free RAM and swap would be a good idea.

监控空闲 RAM 和交换也是一个好主意。

回答by Giampaolo Rodolà

>>> 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

回答by lambeaux

I was working on basically the same thing just a couple of weeks ago and I too was having trouble with psutil.cpu_percent().

几周前我还在做基本相同的事情,我也遇到了 psutil.cpu_percent() 问题。

Instead I used psutil.cpu_times() which gives cpu time used for user, system, idle and other things depending on your OS. I dont know if this is a good way or even an accurate way of doing things.

相反,我使用了 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

回答by u7408681

for psutil,when you run the .py file in shell,the right answer is

对于 psutil,当你在 shell 中运行 .py 文件时,正确的答案是

psutil.cpu_percent(interval=1)

don't forget the argument interval=1,otherwise ,it will return 0 or 100,maybe a bug.

不要忘记参数interval=1,否则,它将返回0或100,可能是一个错误。