嘿,我正在学习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()
运行。
import multiprocessing
import psutil
import random
def iHateThis():
tab = []
for i in range(100000):
tab.append(random.randint(1, 10000))
tab.sort()
return tab;
hate = multiprocessing.Process(name='hate', target=iHateThis)
hate.start()
while(True):
currentProcess = psutil.Process()
print(currentProcess.cpu_percent(interval=1))
您可以使用threading
运行iHateThis
或使用cpu_percent()
运行功能。我选择第二个版本。我将在线程中运行cpu_percent()
。
因为它使用while True
,所以线程将永远运行,并且没有很好的方法来停止线程,所以我将全局变量running
与while running
一起使用来停止该循环。
import threading
import psutil
def display_cpu():
global running
running = True
currentProcess = psutil.Process()
# start loop
while running:
print(currentProcess.cpu_percent(interval=1))
def start():
global t
# create thread and start it
t = threading.Thread(target=display_cpu)
t.start()
def stop():
global running
global t
# use `running` to stop loop in thread so thread will end
running = False
# wait for thread's end
t.join()
现在我可以用它来启动和停止显示CPU的线程。因为我可能必须使用Ctrl+C
停止进程,所以它会引发错误,因此即使有错误,我也会使用try/finally
来停止线程。
def i_hate_this():
tab = []
for i in range(1000000):
tab.append(random.randint(1, 10000))
tab.sort()
return tab
# ---
start()
try:
result = i_hate_this()
finally: # stop thread even if I press Ctrl+C
stop()
完整代码:
import random
import threading
import psutil
def display_cpu():
global running
running = True
currentProcess = psutil.Process()
# start loop
while running:
print(currentProcess.cpu_percent(interval=1))
def start():
global t
# create thread and start it
t = threading.Thread(target=display_cpu)
t.start()
def stop():
global running
global t
# use `running` to stop loop in thread so thread will end
running = False
# wait for thread's end
t.join()
# ---
def i_hate_this():
tab = []
for i in range(1000000):
tab.append(random.randint(1, 10000))
tab.sort()
return tab
# ---
start()
try:
result = i_hate_this()
finally: # stop thread even if I press Ctrl+C
stop()
BTW:可以将其转换为继承自Thread类的类,然后可以将变量running
隐藏在类中。
import psutil
import random
import threading
class DisplayCPU(threading.Thread):
def run(self):
self.running = True
currentProcess = psutil.Process()
while self.running:
print(currentProcess.cpu_percent(interval=1))
def stop(self):
self.running = False
# ----
def i_hate_this():
tab = []
for i in range(1000000):
tab.append(random.randint(1, 10000))
tab.sort()
return tab
# ---
display_cpu = DisplayCPU()
display_cpu.start()
try:
result = i_hate_this()
finally: # stop thread even when I press Ctrl+C
display_cpu.stop()
它也可以转换成上下文管理器以运行它,>]
with display_cpu(): i_hate_this()
但是我跳过了这一部分。