【Python】win10上用psutil统计应用CPU占用情况

win10上用psutil统计应用CPU占用情况

psutil用法可参考:https://blog.csdn.net/qq_45689245/article/details/125409744

对于多进程应用,调用p.cpu_percent()函数会出现值大于100的情况,给人一种不太准确的感觉。

为解决该问题,以统计谷歌浏览器CPU占用情况为例,相关处理逻辑如下:

import psutil


if __name__ == "__main__":
    """
    value = p.cpu_percent(interval=1)
    A value > 100.0 can be returned in case of processes running
    multiple threads on different CPU cores.

    The returned value is explicitly NOT split evenly between
    all available logical CPUs. This means that a busy loop process
    running on a system with 2 logical CPUs will be reported as
    having 100% CPU utilization instead of 50%.
    """
    print("逻辑CPU核数:", psutil.cpu_count())
    print("物理CPU核数:", psutil.cpu_count(logical=False))
    print("CPU的用户、系统、空闲时间:", psutil.cpu_times())
    print("获取每个CPU的使用率,类似TOP命令:", psutil.cpu_percent(percpu=True))
    # 设置每秒刷新时间间隔,统计十次的结果
    # top = [psutil.cpu_percent(interval=1, percpu=True) for i in range(10)]
    # print(top)

    logic_cpu_num = psutil.cpu_count()
    physic_cpu_num = psutil.cpu_count(logical=False)
    total_logic_cpu_usage = 0
    total_physic_cpu_usage = 0
    works = psutil.process_iter()
    app_name = "chrome.exe"
    for p in works:
        if p.name() == app_name:
            if p.is_running():
                with p.oneshot():
                    pid = p.pid
                    process = psutil.Process(pid=pid)
                    cpu_usage = process.cpu_percent(interval=0.1)
                    print("cpu:", cpu_usage, round(cpu_usage / logic_cpu_num, 2))
                    print("#threads:", process.num_threads())
                    total_logic_cpu_usage += cpu_usage / logic_cpu_num
                    total_physic_cpu_usage += cpu_usage / physic_cpu_num

    print(f"[{app_name}]逻辑CPU 占用: {round(total_logic_cpu_usage, 2)}%")
    print(f"[{app_name}]物理CPU 占用: {round(total_physic_cpu_usage, 2)}%")

你可能感兴趣的:(Python,python)