You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python获取CPU、GPU、VPU使用率并实现任务管理器性能页

扩展Python监控脚本:添加GPU、VPU使用率显示

下面是修改后的完整代码,在你原有基础上完善了GPU使用率的显示,并添加了VPU(以Intel VPU为例)的监控功能:

import psutil
import time
import pynvml
from openvino.runtime import Core

# 初始化GPU监控
pynvml.nvmlInit()
gpu_handle = pynvml.nvmlDeviceGetHandleByIndex(0)

# 初始化VPU监控(Intel VPU为例)
ov_core = Core()
vpu_devices = [device for device in ov_core.available_devices if "VPU" in device]
vpu_supported = len(vpu_devices) > 0

def display_usage(cpu_usage, mem_usage, gpu_usage, vpu_usage=None, bars=30):
    # CPU进度条生成
    cpu_percent = cpu_usage / 100.0
    cpu_bar = '█' * int(cpu_percent * bars) + '-' * (bars - int(cpu_percent * bars))
    # 内存进度条生成
    mem_percent = mem_usage / 100.0
    mem_bar = '█' * int(mem_percent * bars) + '-' * (bars - int(mem_percent * bars))
    # GPU进度条生成
    gpu_percent = gpu_usage / 100.0
    gpu_bar = '█' * int(gpu_percent * bars) + '-' * (bars - int(gpu_percent * bars))
    
    # 拼接基础输出内容
    output = f"\rCPU USAGE: |{cpu_bar}| {cpu_usage:.2f}%  "
    output += f"MEM USAGE: |{mem_bar}| {mem_usage:.2f}%  "
    output += f"GPU USAGE: |{gpu_bar}| {gpu_usage:.2f}%  "
    
    # 追加VPU信息(仅当检测到设备时)
    if vpu_usage is not None:
        vpu_percent = vpu_usage / 100.0
        vpu_bar = '█' * int(vpu_percent * bars) + '-' * (bars - int(vpu_percent * bars))
        output += f"VPU USAGE: |{vpu_bar}| {vpu_usage:.2f}%  "
    
    print(output, end="")

while True:
    # 获取CPU与内存使用率
    cpu_usage = psutil.cpu_percent()
    mem_usage = psutil.virtual_memory().percent
    
    # 获取GPU使用率
    gpu_util = pynvml.nvmlDeviceGetUtilizationRates(gpu_handle).gpu
    
    # 获取VPU使用率(Intel VPU)
    vpu_util = None
    if vpu_supported:
        vpu_metrics = ov_core.get_property(vpu_devices[0], "METRIC_DEVICE_UTILIZATION")
        vpu_util = vpu_metrics["utilization"]
    
    # 统一展示所有监控数据
    display_usage(cpu_usage, mem_usage, gpu_util, vpu_util)
    time.sleep(0.5)

关键修改说明

  • 完善GPU监控:原有代码已获取GPU使用率但未传入显示逻辑,现在将其纳入display_usage函数并添加对应进度条展示
  • 添加VPU监控:以Intel VPU为例,采用OpenVINO Runtime库获取设备使用率。若使用其他品牌VPU,需替换对应依赖:
    • Movidius VPU:使用mvncapi库
    • AMD VPU:可调用系统命令amdgpu_top并解析输出,或使用其Python封装
  • 兼容无VPU场景:添加设备检测逻辑,避免无VPU设备时出现运行错误

依赖安装

需额外安装对应库:

  • GPU监控:pip install pynvml(原代码已使用)
  • VPU监控(Intel):pip install openvino
  • CPU/内存监控:pip install psutil(原代码已使用)

内容的提问来源于stack exchange,提问作者Arbaz ali

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 02:07:24