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

相关推荐
林深现海2 小时前
【刘二大人】PyTorch深度学习实践笔记 —— 第四集:反向传播(凝练版)
pytorch·python·numpy
WGS.3 小时前
fastenhancer DPRNN torch 实现
pytorch·深度学习
Rabbit_QL6 小时前
PyTorch DataLoader `num_workers` 配置指南:从新手到进阶
人工智能·pytorch·python
阡陌..7 小时前
pytorch模型训练使用多GPU执行报错:Bus error (core dumped)(未解决)
人工智能·pytorch·python
多恩Stone8 小时前
【3DV 进阶-11】Trellis.2 数据处理与训练流程图
人工智能·pytorch·python·算法·3d·aigc·流程图
爱喝可乐的老王8 小时前
PyTorch搭建神经网络
pytorch·深度学习·神经网络
小饼干超人9 小时前
pytorch返回张量元素总数量的方法 x.numel()
人工智能·pytorch·python
Dfreedom.9 小时前
详解四大格式(PIL/OpenCV/NumPy/PyTorch)的转换原理与场景选择
图像处理·人工智能·pytorch·opencv·numpy·pillow
咚咚王者9 小时前
人工智能之核心技术 深度学习 第九章 框架实操(PyTorch / TensorFlow)
人工智能·pytorch·深度学习
多恩Stone10 小时前
【3DV 进阶-12】Trellis.2 数据处理脚本细节
人工智能·pytorch·python·算法·3d·aigc