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

相关推荐
songyuc9 小时前
【PyTorch】感觉`CrossEntropyLoss`和`BCELoss`很类似,为什么它们接收labels的shape常常不一样呢?
人工智能·pytorch·python
love530love18 小时前
Duix-Avatar 去 Docker Desktop 本地化完整复盘
人工智能·pytorch·windows·python·docker·容器·数字人
郝学胜-神的一滴20 小时前
深度学习入门基石:PyTorch张量核心技术全解析
人工智能·pytorch·python·深度学习·算法·机器学习
hongyuyahei21 小时前
GSPO策略损失完整演示
pytorch·python
sheyuDemo1 天前
torch中的rand()和randn()函数的区别
人工智能·pytorch·深度学习
boy快快长大2 天前
【PyTorch】2.0 入门学习
人工智能·pytorch·学习
Dxy12393102162 天前
PyTorch的自定义学习率调度器详细介绍
人工智能·pytorch·学习
薛不痒2 天前
模型部署:基于flask和pytorch
人工智能·pytorch·python·深度学习·flask
罗罗攀2 天前
PyTorch学习笔记|张量的索引分片、合并和维度调整
人工智能·pytorch·笔记·python·学习
信鸽爱好者2 天前
RTX5060显卡+windows CUDA12.8+cuDNN8.9.7+pytorch安装
人工智能·pytorch·windows·深度学习