【问题标题】:If statement based on percentage usage of certain CPU coresIf 语句基于某些 CPU 内核的百分比使用率
【发布时间】:2021-12-01 14:10:49
【问题描述】:

Python 3.10

假设我有一个这样的 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()}%")

它给出以下输出:

======================================== 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%

我需要补充的是,如果内核 0 到 3 的任何一个使用率超过 50%,那么做一些事情(我知道如何编写代码的做某事部分)。

我将如何编写其中的 if 部分?我被卡住的地方是明确指出核心号码。

我还需要对其他内核执行此操作,有时是所有内核,但如果我看到上面示例的语法,我应该能够弄清楚如何涵盖其他示例。

【问题讨论】:

  • if percentage >= 50.0:?
  • 您在i 中有核心编号,并且您使用if 块来执行逻辑。你被什么困住了?
  • 我只对核心 0-3 感兴趣。我不明白上述逻辑是如何捕捉到这一点的。

标签: python psutil


【解决方案1】:

你应该在 for 循环中编写

if percentage > 50 and i < 4:
    #DO

【讨论】:

  • 我只对核心 0-3 感兴趣。您的代码似乎没有考虑到这一点。
  • 我已经编辑了我的答案以考虑这一点。
  • 啊,好吧,你可以像这样直接调用i 的枚举数。好的,这应该很简单......
  • i(代表索引)只是一个数字,如果你对强类型语言很熟悉的话,它是一个整数。您可以像访问和使用任何其他变量/数字一样简单地访问和使用它
  • 嗯,有道理。感谢您的帮助!
猜你喜欢
  • 1970-01-01
  • 2013-12-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-03
  • 2015-11-05
  • 2011-10-10
  • 2012-11-11
相关资源
最近更新 更多