在Python psutil中调用函数时,如何监视CPU的使用情况?

在Python psutil中调用函数时,如何监视CPU的使用情况?,python,cpu,cpu-usage,psutil,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):

嘿,我正在学习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))

您可以使用
多处理
库执行此操作<代码>多处理。Process是一个表示线程化进程的类,由函数和名称启动,可以随时使用
.start()
运行


您可以使用
threading
运行
iHateThis
或使用
cpu\u percent()
运行函数。我选择第二个版本。我将在线程中运行
cpu\u percent()

因为它使用
而为True
,所以线程将永远运行,并且不会有好的方法停止线程,所以我在运行
时使用全局变量
来停止这个循环

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()

顺便说一句:这可以转换为从类线程继承的类,然后它可以在类中隐藏变量
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()

但是我跳过了这一部分。

我认为您不需要使用psutil
Process
类,因为我认为它是用来监视特定的进程的。使用@furas中的代码片段(公认的答案),您可以使用如下线程:

def run(self):
    self.run = True 
    while self.run:
        psutil.cpu_percent(interval=1)
在以下情况下,其工作原理与接受的答案相同:

    _monitor.start()
    try:
        for i in range(50):
            time.sleep(0.2)
    finally:    
        _monitor.stop()

如果你不想编码它,我在公共回购中这样做,如果它对某人有帮助的话:

你可以在
之前创建
currentProcess
,而
-loopHi,不知道为什么它在控制台中不断显示0.0:/我正在尝试制作真正基本的资源监视器(与windows功能相差无几。可能cpu\u%的功能不正确?我不知道……可能您的计算机速度太快,几乎需要0.0 cpu。我的非常旧的计算机需要98.0。您可以在
范围()中尝试更大的值)
。或者它需要
间隔
小于
1
。我使用LInux,但它在Windows上的工作方式可能不同。您可以使用
打印(psutil.Process().pid)
在线程和主循环中检查线程是否对整个进程的CPU计数,还是只对线程计数。所以我照你说的做了,结果并不乐观…我将范围设置为10000000000000,间隔设置为0.0000000015-没有发生任何事情。我还打印pid,它总是显示相同的numebr例如:996130060601096 etcI不知道。我得到
0.0
仅当我使用其他答案中的代码时,该答案使用
多处理
,因为函数在单独的进程和
psutil.process中运行。process
仅检查当前进程的CPU。但我的代码使用
线程
,它是当前进程的一部分。
    _monitor.start()
    try:
        for i in range(50):
            time.sleep(0.2)
    finally:    
        _monitor.stop()