简体   繁体   English

If 语句基于某些 CPU 内核的百分比使用率

[英]If statement based on percentage usage of certain CPU cores

Python 3.10 Python 3.10

Let's say I have a python script like this:假设我有一个像这样的 python 脚本:

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:这给出了以下 output:

======================================== 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).我需要补充的是,如果内核 0 到 3 中的任何一个使用率超过 50%,那么就做一些事情(我知道如何编写代码的做某事部分)。

How would I write the if part of this?我将如何编写 if 部分? 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.我还需要对其他内核执行此操作,有时甚至是所有内核,但是如果我看到上面示例的语法,我应该能够弄清楚如何涵盖其他示例。

inside the for loop you should write在 for 循环内你应该写

if percentage > 50 and i < 4:
    #DO

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM