aji*_*dyn 3 python cpu cpu-usage psutil
嘿,我正在学习 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))
Run Code Online (Sandbox Code Playgroud)
您可以使用threadingto runiHateThis或 to run function with 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()
Run Code Online (Sandbox Code Playgroud)
现在我可以用它来启动和停止线程,这将显示 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()
Run Code Online (Sandbox Code Playgroud)
完整代码:
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()
Run Code Online (Sandbox Code Playgroud)
顺便说一句:这可以转换为继承自 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()
Run Code Online (Sandbox Code Playgroud)
它还可以转换为上下文管理器来运行它
with display_cpu():
i_hate_this()
Run Code Online (Sandbox Code Playgroud)
但我跳过这一部分。
| 归档时间: |
|
| 查看次数: |
6221 次 |
| 最近记录: |