cpu_percent(interval=None) always returns 0 regardless of interval value PYTHON

江枫思渺然 提交于 2019-12-08 15:57:39

问题


The code always returns 0.0 values, regardless of interval values.

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

回答1:


This behaviour is 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.

There is also a warning against using interval=None for a single call:

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.

If using interval=None, make sure to call .cpu_percent compared to a prior call.

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

instead of:

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



回答2:


The cpu of a Process object is mutable. I have done some tests for you.

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

result: 9.9 0.0 0.0 0.0 0.0 9.9 0.0 9.9 0.0 0.0

So if you want to get the CPU percent of a Process object, you could take the average in certain time.

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)

result: 1.98




回答3:


From my own code that works:

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


来源:https://stackoverflow.com/questions/24367424/cpu-percentinterval-none-always-returns-0-regardless-of-interval-value-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!