PyTorch 测量代码段的运行时间

Contents

timeit

  • timeit. 测量代码开始时刻和结束时刻,然后求差

  • pytorch 的代码经常会运行在 GPU 上,而在 GPU 上的运行都是异步的,意味着采用一般的 timeit 操作不能准确地得到运行时总和,因此我们一般需要用 pytorch 内置的计时工具和同步工具 (单位:ms)
python 复制代码
start = torch.cuda.Event(enable_timing=True)
end = torch.cuda.Event(enable_timing=True)

start.record()
z = x + y
end.record()

# Waits for everything to finish running
torch.cuda.synchronize()

print(start.elapsed_time(end))

profile

  • profile. pytorch 自带或者第三方的代码耗时工具

  • timeit 的方法测试一些小代码还勉强适用,但是在大规模的测试中显然会变得很麻烦,当然,你可以通过添加修饰器的方式去简化一行行重复人工添加这些时间测量代码的枯燥,但是这也并不是最好的解决方案
  • 幸运的是,pytorch 自带了 profile 用于计算模型每个部分耗时 ,其既可以计算 cpu 耗时,也可以计算 gpu 耗时
python 复制代码
x = torch.randn((1, 1), requires_grad=True)
with torch.autograd.profiler.profile(enabled=True) as prof:
	for _ in range(100):  # any normal python code, really!
    	y = x ** 2
print(prof.key_averages().table(sort_by="self_cpu_time_total"))

References

相关推荐
梦想画家4 小时前
基于PyTorch的时间序列异常检测管道构建指南
人工智能·pytorch·python
倦王9 小时前
Pytorch 预训练网络加载与迁移学习基本介绍
人工智能·pytorch·迁移学习
西柚小萌新11 小时前
【深入浅出PyTorch】--8.1.PyTorch生态--torchvision
人工智能·pytorch·python
十子木12 小时前
C++ 类似pytorch的库,工具包,或者机器学习的生态
c++·pytorch·机器学习
FriendshipT17 小时前
图像生成:PyTorch从零开始实现一个简单的扩散模型
人工智能·pytorch·python
zhan11451420 小时前
解析平面卷积/pytorch的nn.Conv2d的计算步骤,in_channels与out_channels如何计算而来
人工智能·pytorch·深度学习·cnn·卷积神经网络
Xander W21 小时前
基于K8s集群的PyTorch DDP 框架分布式训练测试(开发机版)
人工智能·pytorch·分布式·python·深度学习·kubernetes
Wah-Aug21 小时前
基于 PyTorch 的 UNet 与 NestedUNet 图像分割
人工智能·pytorch·计算机视觉
MDLZH2 天前
WSL实践二
人工智能·pytorch·深度学习
倦王2 天前
PyTorch图片数据载入方法
人工智能·pytorch·python