psutil
psutil copied to clipboard
[Linux] `cpu_percent` does not work within `oneshot` context manager as expected
Summary
- OS: Ubuntu 20.04
- Architecture: x86 64bit
- Psutil version: 5.8.0
- Python version: 3.8.10
- Type: doc, core (?)
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-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
Just checked the behaviour -- it's the same for the newer 5.9.0 version.