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

Nihal Harish picture Nihal Harish · Jun 23, 2014 · Viewed 9.1k times · Source

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)

Answer

whypro picture whypro · Dec 1, 2014

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