cpu_percent(interval=None)总是返回0,而不考虑间隔值PYTHON

2024-04-25 05:29:29 发布

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

无论间隔值如何,代码始终返回0.0值。

import psutil
p = psutil.Process()
print p.cpu_percent(interval=1)
print p.cpu_percent(interval=None)

Tags: 代码importnone间隔cpuprocesspsutilprint
3条回答

根据我自己的代码:

cpu = psutil.cpu_times_percent(interval=0.4, percpu=False)

进程对象的cpu是可变的。我给你做了一些测试。

for i in range(10):
    p = psutil.Process(3301)
    print p.cpu_percent(interval=0.1)

结果: 9.9 0.0 0.0 0.0 0.0 9.9 0.0 9.9 0.0 0.0

所以如果你想得到一个进程对象的CPU百分比,你可以在一定时间内取平均值。

test_list = []
for i in range(10):
    p = psutil.Process(6601)
    p_cpu = p.cpu_percent(interval=0.1)
    test_list.append(p_cpu)
print float(sum(test_list))/len(test_list)

结果: 1.98

More info in picture

这种行为是documented

When interval is 0.0 or None compares process times to system CPU times elapsed since last call, returning immediately. That means the first time this is called it will return a meaningless 0.0 value which you are supposed to ignore. In this case is recommended for accuracy that this function be called a second time with at least 0.1 seconds between calls.

还有一个警告,禁止对单个调用使用interval=None

Warning: the first time this function is called with interval = 0.0 or None it will return a meaningless 0.0 value which you are supposed to ignore.

如果使用interval=None,请确保与以前的调用相比调用.cpu_percent

p = psutil.Process(pid=pid)
p.cpu_percent(interval=None)
for i in range(100):
    usage = p.cpu_percent(interval=None)
    # do other things

而不是:

for i in range(100):
    p = psutil.Process(pid=pid)
    p.cpu_percent(interval=None)
    # do other things

相关问题 更多 >