Home > OS >  Printing python CPU count not working from terminal
Printing python CPU count not working from terminal

Time:12-03

Situation

I am in the situation in which I want to run a script from terminal which prints the used CPU percentage per cpu. I wrote this simple script.

import psutil 

values = psutil.cpu_percent(percpu=True) 
print(f"{'CPU':>3} {'CPU%':>6}")
print(10*'=')
for cpu in range(1, psutil.cpu_count() 1):
    print(f"{cpu:<3} {values[cpu-1]:>5}%")

When I run this in a Jupyter Notebook cell I get what I want, which is per CPU the currently used percentage. Something like this

CPU   CPU%
==========
1   100.0%
2     1.5%
3     1.3%
4     0.8%
5     0.1%
6     0.9%
7     1.0%
8     0.2%

Issue

Now I put the above code in a python file get_cpu_perc.py and run the script from my terminal

python3 get_cpu_perc.py

What is getting printed on the terminal is always

CPU   CPU%
==========
1     0.0%
2     0.0%
3     0.0%
4     0.0%
5     0.0%
6     0.0%
7     0.0%
8     0.0%

Question

What is happening here? Why is it never showing the percentage when I run the script from the terminal?

CodePudding user response:

psutil needs some time to measure your cpu usage. This is usually done between import of psutil and the first call. It might be that in your jupyter notebook there is more time between the import and the readout.

You can pause the program for a short amount of time in order to force psutil to 'listen' to your cpu:

# listen to the cpu for 0.1 seconds before returning the value
values = psutil.cpu_percent(interval=0.1, percpu=True)

Then the values should fill up.

  • Related