在Python终端下动态绘制显卡使用率和内存占用率的折线图,可以使用matplotlib
库来实现。为了获取显卡的使用率和内存占用率,可以使用GPUtil
库。以下是一个完整的示例代码:
首先,确保你已经安装了matplotlib
和GPUtil
库。如果没有安装,可以使用以下命令进行安装:
pip install matplotlib GPUtil
import time
import matplotlib.pyplot as plt
import GPUtil
# 初始化数据存储
gpu_usage = []
gpu_memory = []
timestamps = []
# 创建图形
plt.ion() # 开启交互模式
fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(10, 8))
# 设置图形标题和标签
ax1.set_title('GPU Usage Over Time')
ax1.set_ylabel('Usage (%)')
ax2.set_title('GPU Memory Usage Over Time')
ax2.set_ylabel('Memory Usage (MB)')
ax2.set_xlabel('Time (s)')
# 初始化折线图
line1, = ax1.plot(timestamps, gpu_usage, 'r-', label='GPU Usage')
line2, = ax2.plot(timestamps, gpu_memory, 'b-', label='GPU Memory Usage')
# 添加图例
ax1.legend()
ax2.legend()
# 动态更新图形
start_time = time.time()
while True:
# 获取GPU信息
gpus = GPUtil.getGPUs()
if gpus:
gpu = gpus[0] # 假设只有一个GPU
current_time = time.time() - start_time
gpu_usage.append(gpu.load * 100)
gpu_memory.append(gpu.memoryUsed)
timestamps.append(current_time)
# 更新折线图数据
line1.set_xdata(timestamps)
line1.set_ydata(gpu_usage)
line2.set_xdata(timestamps)
line2.set_ydata(gpu_memory)
# 调整坐标轴范围
ax1.relim()
ax1.autoscale_view()
ax2.relim()
ax2.autoscale_view()
# 重绘图形
fig.canvas.draw()
fig.canvas.flush_events()
# 每隔1秒更新一次
time.sleep(1)
将上述代码保存为一个Python文件(例如gpu_monitor.py
),然后在终端中运行:
python gpu_monitor.py
通过这种方式,你可以在Python终端下动态监控并绘制显卡的使用率和内存占用率。