PyTorch torch.cuda.memory_reserved 函数
torch.cuda.memory_reserved 是 PyTorch 中用于获取已保留显存的函数。返回 CUDA 缓存管理器当前保留的内存大小(以字节为单位)。
函数定义
torch.cuda.memory_reserved(device=None)
使用示例
实例
import torch
# 检查已保留显存
if torch.cuda.is_available():
print(f"Initial memory reserved: {torch.cuda.memory_reserved()} bytes")
# 创建张量
x = torch.randn(1000, 1000).cuda()
print(f"After allocation: {torch.cuda.memory_reserved()} bytes")
# 删除张量
del x
print(f"After deletion: {torch.cuda.memory_reserved()} bytes")
else:
print("CUDA not available")
# 检查已保留显存
if torch.cuda.is_available():
print(f"Initial memory reserved: {torch.cuda.memory_reserved()} bytes")
# 创建张量
x = torch.randn(1000, 1000).cuda()
print(f"After allocation: {torch.cuda.memory_reserved()} bytes")
# 删除张量
del x
print(f"After deletion: {torch.cuda.memory_reserved()} bytes")
else:
print("CUDA not available")

Pytorch torch 参考手册