嘿,我正在学习psutil软件包,我想知道如何在功能进行时显示当前的CPU使用情况?我想我需要穿线之类的东西,但是怎么做呢?谢谢你的回答
import psutil
import random
def iHateThis():
tab = []
for i in range(100000):
tab.append(random.randint(1, 10000))
tab.sort()
return tab;
while(True):
currentProcess = psutil.Process()
print(currentProcess.cpu_percent(interval=1))
您可以使用
multiprocessing
库来实现这一点multiprocessing.Process
是一个表示线程化进程的类,使用函数和名称启动,并且可以随时使用.start()
运行您可以使用
threading
运行iHateThis
或使用cpu_percent()
运行函数。我选择第二个版本。我将在线程中运行cpu_percent()
因为它使用
while True
,所以线程将永远运行,并且没有好的方法来停止线程,所以我使用全局变量running
和while running
来有方法来停止这个循环现在我可以用它来启动和停止显示CPU的线程。因为我可能必须使用
Ctrl+C
停止进程,所以它会引发错误,所以我使用try/finally
停止线程,即使会出现错误完整代码:
顺便说一句:这可以转换为从类线程继承的类,然后它可以在类中隐藏变量
running
还可以将其转换为上下文管理器以作为
但我跳过这部分
我认为您不需要使用psutil
Process
类,因为我认为它是用于监视特定进程的。使用@furas中的代码片段(公认的答案),您可以使用如下线程:在以下情况下,其工作原理与接受的答案相同:
如果您不想编写代码,我将在公共回购协议中这样做,如果它对某人有任何帮助:https://github.com/GTimothee/monitor
相关问题 更多 >
编程相关推荐