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

相关推荐
伊织code5 小时前
PyTorch API 7
pytorch·api·张量·稀疏
聚客AI7 小时前
深度拆解AI大模型从训练框架、推理优化到市场趋势与基础设施挑战
图像处理·人工智能·pytorch·深度学习·机器学习·自然语言处理·transformer
大力水手(Popeye)10 小时前
Pytorch——tensor
人工智能·pytorch·python
Caven7718 小时前
【pytorch】reshape的使用
pytorch·python
无规则ai18 小时前
动手学深度学习(pytorch版):第四章节—多层感知机(5)权重衰减
人工智能·pytorch·python·深度学习
雷达学弱狗1 天前
backward怎么计算的是torch.tensor(2.0, requires_grad=True)变量的梯度
人工智能·pytorch·深度学习
抠头专注python环境配置1 天前
Pytorch GPU版本安装保姆级教程
pytorch·python·深度学习·conda
爱分享的飘哥2 天前
第七十章:告别“手写循环”噩梦!Trainer结构搭建:PyTorch Lightning让你“一键炼丹”!
人工智能·pytorch·分布式训练·lightning·accelerate·训练框架·trainer
盛世隐者2 天前
【深度学习】pytorch深度学习框架的环境配置
人工智能·pytorch·深度学习
EthanLifeGreat2 天前
ParallelWaveGAN-KaldiFree:纯Pytorch的PWG
人工智能·pytorch·深度学习·音频·语音识别