You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
importsubprocessimporttimeimportpsutil# type: ignoreprocess=psutil.Process()
interval=5# Main process testprocess.cpu_percent(interval=None)
print(f'Main {process}{process.cpu_times()}')
t=time.time()
whiletime.time() -t<interval:
passcpu_usage=process.cpu_percent(interval=None)
print(f'Main {process}{process.cpu_times()}')
print(f'Main CPU (%): {cpu_usage} (expecting ~100)')
# Child process testcmd=f'''keep_cpu_busy() {{ end=$((SECONDS+{interval})) while [ $SECONDS -lt $end ]; do : done}}keep_cpu_busy'''p=subprocess.Popen(['bash', '-c', cmd])
forchildinprocess.children(recursive=True):
child.cpu_percent(interval=None)
print(f'Child {child}{child.cpu_times()}')
cpu_usage=0time.sleep(interval-1)
forchildinprocess.children(recursive=True):
cpu_usage+=child.cpu_percent(interval=None)
print(f'Child {child}{child.cpu_times()}')
print(f'Child CPU (%): {cpu_usage} (expecting ~100)')
p.wait()
Basically, cpu_usage works as expected for the main process, but not for the child spawned with subprocess.Popen, expecting ~100 but getting 0.0 instead.
The text was updated successfully, but these errors were encountered:
...creates a set of brand new Process instances, upon which you immediately call cpu_percent(). They have no knowledge of what happened before, nor they have a big enough time window to calculate a meaningful percent value, hence they return 0.
From the doc:
the first time this cpu_percent() is called with interval = 0.0 or None it will return a meaningless 0.0 value which you are supposed to ignore
I was assuming there is a state stored outside the psutil.Process instance, since the pcputimes.user value is consistent with the actual child that exists before its psutil twin instantiation.
And I could argue the documentation is confusing, because child.cpu_percent() is being called a first time (so as to ignore its meaningless 0.0 value), according to the PID, but not according to the psutil instance.
And I could argue the documentation is confusing, because child.cpu_percent() is being called a first time (so as to ignore its meaningless 0.0 value), according to the PID, but not according to the psutil instance.
I read it twice but I don't understand what you mean here. If you have suggestions on how to reword the doc please go for it.
Summary
Description
Replicable code:
Basically, cpu_usage works as expected for the main process, but not for the child spawned with subprocess.Popen, expecting ~100 but getting 0.0 instead.
The text was updated successfully, but these errors were encountered: