Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

If statement based on percentage usage of certain CPU cores

Python 3.10

Let’s say I have a python script like this:

import psutil

print("="*40, "CPU Info", "="*40)
print("Physical cores:", psutil.cpu_count(logical=False))
print("Total cores:", psutil.cpu_count(logical=True))
print("CPU Usage Per Core:")
for i, percentage in enumerate(psutil.cpu_percent(percpu=True, interval=1)):
    print(f"Core {i}: {percentage}%")
print(f"Total CPU Usage: {psutil.cpu_percent()}%")

Which gives the following output:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

======================================== CPU Info ========================================
Physical cores: 4
Total cores: 8
CPU Usage Per Core:
Core 0: 13.6%
Core 1: 1.5%
Core 2: 18.5%
Core 3: 0.0%
Core 4: 16.9%
Core 5: 7.7%
Core 6: 9.2%
Core 7: 9.2%
Total CPU Usage: 9.7%

What I need to be able to add to this is, if any of cores 0 through 3 are above 50% usage, then do something (I know how to write the do something part of the code).

How would I write the if part of this? Where I’m stuck is indicating the core numbers explicitly.

I will also be required to do this with other cores, and sometimes all of them, but if I see the syntax for my above example, I should be able to figure out how to cover other examples.

>Solution :

inside the for loop you should write

if percentage > 50 and i < 4:
    #DO
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading