现在位置: 首页 > PyTorch 教程 > 正文

PyTorch torch.cuda.memory_allocated 函数


Pytorch torch 参考手册 Pytorch torch 参考手册

torch.cuda.memory_allocated 是 PyTorch 中用于获取已分配显存的函数。返回当前 CUDA 设备已分配的内存大小(以字节为单位)。

函数定义

torch.cuda.memory_allocated(device=None)

使用示例

实例

import torch

# 检查已分配显存
if torch.cuda.is_available():
    print(f"Initial memory: {torch.cuda.memory_allocated()} bytes")

    # 创建张量
    x = torch.randn(1000, 1000).cuda()
    print(f"After allocation: {torch.cuda.memory_allocated()} bytes")

    # 删除张量
    del x
    print(f"After deletion: {torch.cuda.memory_allocated()} bytes")
else:
    print("CUDA not available")

Pytorch torch 参考手册 Pytorch torch 参考手册