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

相关推荐
70asunflower3 小时前
torch.manual_seed()介绍
人工智能·pytorch·python
sunfove8 小时前
拥抱不确定性:使用 PyTorch 构建贝叶斯神经网络 (BNN)
人工智能·pytorch·神经网络
bst@微胖子18 小时前
LlamaIndex之核心概念及部署以及入门案例
pytorch·深度学习·机器学习
C系语言1 天前
Anaconda虚拟环境,完全使用conda install命令安装所有包,使用conda install pytorch
人工智能·pytorch·conda
不如语冰2 天前
AI大模型入门1.1-python基础-数据结构
数据结构·人工智能·pytorch·python·cnn
pen-ai2 天前
PyTorch 张量维度处理详解
人工智能·pytorch·python
pen-ai2 天前
【PyTorch】 nn.TransformerEncoderLayer 详解
人工智能·pytorch·python
山土成旧客2 天前
【Python学习打卡-Day44】站在巨人的肩膀上:玩转PyTorch预训练模型与迁移学习
pytorch·python·学习
星河天欲瞩2 天前
【深度学习Day1】环境配置(CUDA、PyTorch)
人工智能·pytorch·python·深度学习·学习·机器学习·conda
猫天意3 天前
【深度学习小课堂】| torch | 升维打击还是原位拼接?深度解码 PyTorch 中 stack 与 cat 的几何奥义
开发语言·人工智能·pytorch·深度学习·神经网络·yolo·机器学习