Not sure if this is a bug, but this behaviour is not documented at all and has left me scratching my head for couple of hours. Basically, cpu_percent method does not work as described with non-zero interval argument when called in oneshot context. My test scripts:
With oneshot
import psutil
p = psutil.Process(41264)
with p.oneshot():
print(p.cpu_percent(interval=0.5))
prints 0.0
With oneshot and explicit sleep
import psutil
import time
p = psutil.Process(41264)
with p.oneshot():
p.cpu_percent()
time.sleep(0.5)
print(p.cpu_percent())
prints 0.0
Without context manager
import psutil
p = psutil.Process(41264)
print(p.cpu_percent(interval=0.5))
Prints 16.0 or other non-zero value, as expected.
Suggestions
If this is by design, I think it should be mentioned in the documentation under oneshot and/or cpu_percent descriptions. Currently documentation for the context manager lists cpu_percent among methods that gain a speedup from it and even shows a code that doesn't seem to work:
with p.oneshot():
p.cpu_percent() # return cached value
Summary
Description
Not sure if this is a bug, but this behaviour is not documented at all and has left me scratching my head for couple of hours. Basically,
cpu_percent
method does not work as described with non-zerointerval
argument when called inoneshot
context. My test scripts:With
oneshot
prints
0.0
With
oneshot
and explicitsleep
prints
0.0
Without context manager
Prints
16.0
or other non-zero value, as expected.Suggestions
If this is by design, I think it should be mentioned in the documentation under
oneshot
and/orcpu_percent
descriptions. Currently documentation for the context manager listscpu_percent
among methods that gain a speedup from it and even shows a code that doesn't seem to work: