画图时使用的函数和一些错误处理

 1. 关于 画图时后的数据量匹配错误(应该是)

然后这块还有个问题:

import pynvml
import matplotlib.pyplot as plt
import matplotlib.animation as animation

def get_gpu_memory_usage(handle):
    gpu_mem = pynvml.nvmlDeviceGetMemoryInfo(handle)
    return gpu_mem.used / 1024 ** 2  # Convert memory usage to MB

def animate(i, ys, handle):
    ys.append(get_gpu_memory_usage(handle))
    ys = ys[-100:]
    line.set_ydata(ys)
    return line,

if __name__ == "__main__":
    pynvml.nvmlInit()
    handle = pynvml.nvmlDeviceGetHandleByIndex(0)  # Assuming you have only one GPU

    fig, ax = plt.subplots()
    line, = ax.plot([], [])
    ax.set_xlim(0, 100)
    ax.set_ylim(0, 10000)  # Assuming the maximum GPU memory is 10000 MB
    ax.set_title('Real-time GPU Memory Usage')
    ax.set_xlabel('Time')
    ax.set_ylabel('Memory Usage (MB)')

    ys = [0] * 100

    ani = animation.FuncAnimation(fig, animate, fargs=(ys, handle), interval=1000)

    plt.show()

    pynvml.nvmlShutdown()

出现这个错:"ValueError: shape mismatch: objects cannot be broadcast to a single shape. Mismatch is between arg 0 with shape (0,) and arg 1 with shape (100,)."

把:

def animate(i, ys, handle):
    # update GPU memory usage
    ys.append(get_gpu_memory_usage(handle))
    ys = ys[-100:]
    line.set_ydata(ys)
    return line,

改为:

def animate(i, ys, handle):
    ys.append(get_gpu_memory_usage(handle))
    ys = ys[-100:]
    line.set_data(range(len(ys)), ys)  # Set both x and y data
    ax.set_xlim(0, len(ys))  # Adjust x-axis limit based on the length of ys
    return line,    # 用于指示函数应返回包含 line 值的元组。
                    # 在 Python 中,单项元组必须有一个尾随逗号,以将其与括号内的普通表达式区分开。

就不报错

2. 解决数据堆在一起的问题:

如下图所示例,这样数据就很不好看:

画图时使用的函数和一些错误处理_第1张图片

想让数据不要挤在一起,就可以让 横轴范围变小:

# 设置横坐标范围
# 由 +1000 变为 +10
# plt.xlim(0, max(x) + 10000)
plt.xlim(0, max(x) + 10)

你可能感兴趣的:(python)