初始化GPU显存监控器 Args: gpu_index: 要监控的GPU索引,默认0 interval: 监控间隔时间(秒),默认1秒 unit: 返回的单位,支持 'MB' 或 'GB',默认'GB'
(self, gpu_index=0, interval=1.0, unit='GB')
| 7 | |
| 8 | class GPUMemoryMonitor: |
| 9 | def __init__(self, gpu_index=0, interval=1.0, unit='GB'): |
| 10 | """ |
| 11 | 初始化GPU显存监控器 |
| 12 | |
| 13 | Args: |
| 14 | gpu_index: 要监控的GPU索引,默认0 |
| 15 | interval: 监控间隔时间(秒),默认1秒 |
| 16 | unit: 返回的单位,支持 'MB' 或 'GB',默认'GB' |
| 17 | """ |
| 18 | self.gpu_index = gpu_index |
| 19 | self.interval = interval |
| 20 | self.unit = unit.upper() |
| 21 | |
| 22 | # 验证单位参数 |
| 23 | if self.unit not in ['MB', 'GB']: |
| 24 | raise ValueError("单位必须是 'MB' 或 'GB'") |
| 25 | |
| 26 | # 监控相关状态 |
| 27 | self.monitor_thread = None |
| 28 | self._running = False |
| 29 | self._lock = threading.Lock() |
| 30 | self.peak_memory_usage = 0 # 峰值显存使用量 |
| 31 | self.start_time = None |
| 32 | self.stop_time = None |
| 33 | |
| 34 | # 初始化NVML |
| 35 | try: |
| 36 | pynvml.nvmlInit() |
| 37 | self.device_count = pynvml.nvmlDeviceGetCount() |
| 38 | if self.gpu_index >= self.device_count: |
| 39 | raise ValueError(f"GPU索引 {self.gpu_index} 超出范围,系统只有 {self.device_count} 个GPU") |
| 40 | self.handle = pynvml.nvmlDeviceGetHandleByIndex(self.gpu_index) |
| 41 | |
| 42 | # 获取GPU名称 |
| 43 | self.gpu_name = pynvml.nvmlDeviceGetName(self.handle) |
| 44 | |
| 45 | except Exception as e: |
| 46 | print(f"初始化NVML失败: {e}") |
| 47 | if 'pynvml' in sys.modules: |
| 48 | pynvml.nvmlShutdown() |
| 49 | raise |
| 50 | |
| 51 | def _get_memory_info(self): |
| 52 | """获取当前GPU显存信息""" |
nothing calls this directly
no outgoing calls
no test coverage detected