I'm attempting to use the psutil python library to measure CPU utilisation over time for the current process (os.getpid()). The script is intended to print values of the CPU usage over each 1 second interval. The simulated average load is intended to be quite low (~1%), to be similar to the real process I will measure.
The problem is that psutil seems to report values of 0.0% usage some of the time, which doesn't make sense over a 1s interval (note the 0.1s sleep time in the simulated load function). Can someone please help me to understand the values psutil is reporting or point out if I'm misusing it in some way.
Thanks!
versions
python = 3.10.8 psutil = 5.9.0
import time
import random
import psutil
import threading
test_time = 10
start_time = time.perf_counter()
def simulate_load():
while time.perf_counter() - start_time < test_time:
c = 0
for _ in range(350):
c += random.randint(0, 5)
time.sleep(0.1)
def measure_load():
log = []
this_process = psutil.Process()
this_process.cpu_affinity([15])
this_process.cpu_percent(interval=0)
while time.perf_counter() - start_time < test_time:
log.append(this_process.cpu_percent(interval=0))
time.sleep(1)
return log
background_thread = threading.Thread(target=simulate_load)
background_thread.start()
print(measure_load())
output
[0.0, 1.6, 1.5, 0.0, 1.6, 1.5, 0.0, 0.0, 0.0, 3.1]
range(350)is way too low for you to notice something on a modern computer. Try withrange(1e6)for example.For 350, I got: [0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0]
For 1e6 : [186.3, 81.1, 80.1, 89.4, 89.4, 90.4, 79.5, 80.5, 78.5, 82.6]
Interesting numbers and orders of magnitude reference table.