pytorch查看gpu
时间: 2025-02-01 15:02:08 浏览: 44
### 查看PyTorch中的GPU使用情况
在PyTorch环境中,可以利用`torch.cuda`模块下的多个函数来查询和管理GPU资源。例如,要查看当前设备上的显存占用状况以及确认张量或其他CUDA对象所分配的具体显卡编号。
对于获取详细的GPU内存统计信息,可以通过调用`torch.cuda.memory_stats()`方法实现[^1]:
```python
import torch
# 获取所有可用的gpu数量
device_count = torch.cuda.device_count()
print(f"Number of available GPUs: {device_count}")
# 设置默认使用的GPU ID, 假设只有一块GPU则设置为0
current_device = 0
if device_count > 0:
# 显示当前激活的cuda设备名称
print(torch.cuda.get_device_name(current_device))
# 打印已分配给程序运行过程中的最大内存量(单位字节)
max_allocated_memory = torch.cuda.max_memory_allocated(device=current_device)
print(f"Max allocated memory on GPU-{current_device}: {max_allocated_memory / (1024 ** 2):.2f} MB")
# 清理缓存以释放未被引用但仍占据空间的数据
torch.cuda.empty_cache()
# 输出完整的GPU内存统计数据
stats = torch.cuda.memory_stats(current_device)
for key, value in stats.items():
print(f"{key}: {value}")
```
此外,在多进程或多线程环境下操作时需要注意同步问题;当遇到异常退出等情况可能导致某些临时文件未能及时清理干净,这时可能需要手动清除残留文件或重启计算节点才能恢复正常工作状态。
阅读全文
相关推荐


















