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

相关推荐
兜兜风d'5 小时前
PyTorch 深度学习实践——加载数据集
人工智能·pytorch·深度学习
一碗姜汤5 小时前
torch.autograd.Function的apply()方法作用
人工智能·pytorch·深度学习
Galerkin码农选手6 小时前
per_tenor_quant_fp8和per_token_quant_fp8算法解读
人工智能·pytorch·算法
Fleshy数模7 小时前
基于PyTorch实现MNIST手写数字识别——卷积神经网络实战
人工智能·pytorch·cnn
兜兜风d'7 小时前
PyTorch 深度学习实践——多分类问题
pytorch·深度学习·分类
Dxy12393102167 小时前
PyTorch的StepLR详细介绍:深度学习训练的“定时减速”战术
人工智能·pytorch·深度学习
兜兜风d'7 小时前
PyTorch 深度学习实践——RNN循环神经网络
人工智能·pytorch·rnn·深度学习
快乐非自愿7 小时前
深度解析:PyTorch 2.0 下的深度学习模型训练全流程
人工智能·pytorch·深度学习
zhangfeng11338 小时前
unsloth 安装在google colab
pytorch·python·深度学习
<-->9 小时前
SGLang 相比 vLLM 的主要优势
人工智能·pytorch·python·transformer