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

相关推荐
剑穗挂着新流苏3123 小时前
204_从回归到分类:Softmax 回归、损失函数与多分类实战
人工智能·pytorch·python·深度学习
独隅14 小时前
PyTorch 模型部署的 Docker 配置与性能调优深入指南
人工智能·pytorch·docker
靴子学长16 小时前
Decoder only 架构下 - KV cache 的理解
pytorch·深度学习·算法·大模型·kv
独隅17 小时前
PyTorch 模型性能优化:图像分类与 NLP 模型实战指南
pytorch·性能优化·分类
Narrastory18 小时前
明日香 - Pytorch 快速入门保姆级教程(九)
人工智能·pytorch·深度学习
AI视觉网奇19 小时前
vllm 踩坑记录 算力匹配
pytorch·python·深度学习
剑穗挂着新流苏3121 天前
202_深度学习的动力源泉:矩阵微积分与自动求导 (Autograd)
人工智能·pytorch·python·深度学习·神经网络
每天吃的很好的Ruby1 天前
报错ValueError: sampler option is mutually exclusive with shuffle
人工智能·pytorch·python
Chasing Aurora1 天前
Python后端开发之旅(五)——DL
开发语言·pytorch·python·深度学习
AI-Ming1 天前
程序员转行学习 AI 大模型: 模型微调| 附清晰概念分类
人工智能·pytorch·深度学习·机器学习·chatgpt·nlp·gpt-3