Title: Check CPU usage in Python
This is another unglamorous example that may be useful under some circumstances. It's super short so here it is in its entirety.
import psutil
cpu_percent = psutil.cpu_percent(interval=1)
print(f'CPU: {cpu_percent / 100:.2%}')
The psutil.cpu_percent function returns the fraction of the CPU time used. The interval parameter tells it how long to wait while tallying the usage. In this example, it gets the CPU usage statistics, waits 1 second, gets the statistics again, and compares the two values to see how much the CPU was used during that 1 second.
That's all there is to it. Download the example to experiment with it and to see additional details.
|