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

相关推荐
盼小辉丶8 小时前
PyTorch实战(30)——使用TorchScript和ONNX导出通用PyTorch模型
人工智能·pytorch·深度学习·模型部署
封奚泽优12 小时前
使用mmdetection项目进行训练记录
pytorch·python·cuda·mmdetection·mmcv
tony36512 小时前
pytorch分布式训练解释
人工智能·pytorch·分布式
weixin_贾12 小时前
深度学习基础理论与 PyTorch 实战 —— 从传统机器学习到前沿模型全攻略
pytorch·深度学习·机器学习
大连好光景1 天前
PyTorch深度学习----优化器
pytorch·深度学习·学习
多恩Stone2 天前
【3D-AICG 系列-11】Trellis 2 的 Shape VAE 训练流程梳理
人工智能·pytorch·算法·3d·aigc
隔壁大炮2 天前
08. PyTorch_张量基本创建方式
人工智能·pytorch·python
隔壁大炮2 天前
07. PyTorch框架简介
人工智能·pytorch·python
大鹏的NLP博客3 天前
Rust + PyTorch 实现 BGE 向量检索系统
人工智能·pytorch·rust
勾股导航4 天前
蚁群优化算法
人工智能·pytorch·python