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

相关推荐
递归不收敛5 小时前
吴恩达机器学习课程(PyTorch适配)学习笔记:1.3 特征工程与模型优化
pytorch·学习·机器学习
星期天要睡觉7 小时前
模型部署——Flask 部署 PyTorch 模型
pytorch·python·flask
西柚小萌新7 小时前
【深入浅出PyTorch】--4.PyTorch基础实战
人工智能·pytorch·python
小虎鲸009 小时前
PyTorch的安装与使用
人工智能·pytorch·python·深度学习
weixin_4334176713 小时前
PyTorch&TensorFlow
人工智能·pytorch·tensorflow
lyx33136967591 天前
#深度学习基础:神经网络基础与PyTorch
pytorch·深度学习·神经网络·参数初始化
递归不收敛1 天前
吴恩达机器学习课程(PyTorch 适配)学习笔记:3.3 推荐系统全面解析
pytorch·学习·机器学习
JJJJ_iii1 天前
【深度学习03】神经网络基本骨架、卷积、池化、非线性激活、线性层、搭建网络
网络·人工智能·pytorch·笔记·python·深度学习·神经网络
JJJJ_iii1 天前
【深度学习05】PyTorch:完整的模型训练套路
人工智能·pytorch·python·深度学习
荼蘼1 天前
使用 Flask 实现本机 PyTorch 模型部署:从服务端搭建到客户端调用
人工智能·pytorch·python