giampaolo / psutil

Cross-platform lib for process and system monitoring in Python
BSD 3-Clause "New" or "Revised" License
10.32k stars 1.39k forks source link

[Linux] `cpu_percent` does not work within `oneshot` context manager as expected #2072

Open nj-vs-vh opened 2 years ago

nj-vs-vh commented 2 years ago

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-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
nj-vs-vh commented 2 years ago

Just checked the behaviour -- it's the same for the newer 5.9.0 version.