python psutil库中的cpu_usage()显示100%的cpu使用率,但HWMonitor仅显示1011%?

2024-10-05 14:28:47 发布

您现在位置:Python中文网/ 问答频道 /正文

如上所述,为什么函数cpu_使用率显示100%的cpu,而在HWMonitor或Windows任务管理器中,我只能看到10-11%的使用率。我得到了一些测量cpu和ram使用率的代码。内存使用似乎很有魅力,但这个cpu不知何故比任务管理器中的要大10倍。为什么?

import random
import threading
import psutil

def display_cpu():
    global running

    running = True

    currentProcess = psutil.Process()

    # start loop
    while running:
        print("CPU: ",currentProcess.cpu_percent(interval=1), "%", "| Memory: ", currentProcess.memory_info().rss/(1024*1024), "MB")

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 insertion_sort():
    nums = []
    for i in range(30000):
        nums.append(random.randint(1, 10000))
    for i in range(1, len(nums)):
        item_to_insert = nums[i]

        j = i - 1

        while j >= 0 and nums[j] > item_to_insert:
            nums[j + 1] = nums[j]
            j -= 1

        nums[j + 1] = item_to_insert


# ---
for i in range(1):
    start()
    try:
        result = insertion_sort()
    finally:
        stop()

Tags: toinimportfordefrangecpuglobal