Pytorch的加法细节操作,提高运算速度

Fawziya ·
更新时间:2024-09-21
· 599 次阅读

Pytorch 加法操作: 1. +

这个是最直接的加法。

res = x + y 2. torch.add()

pytorch 官网提供的一种加法函数。

res = torch.add(x, y) # 也可以指定加法结果输出对象 torch.add(x, y, out=result) 3. .add_()

这个是Tensor类的方法。

res = y.add_(x) 加法速度比较:

这么多的加法操作,哪个更稳定速度更快?

实例: import torch import time x = torch.rand(5, 3) y = torch.rand(5, 3) start = time.time() res_1 = x + y print("res_1 output: \n",res_1) print("res_1: ", time.time() - start) start = time.time() res_2 = torch.add(x, y) print("res_2 output: \n",res_2) print("res_2: ", time.time() - start) start = time.time() res_3 = x.add_(y) print("res_3 output: \n",res_3) print("res_3: ", time.time() - start) 结果截图:

情况1:直接输出运算时间:
在这里插入图片描述
情况2:输出运算结果与运算时间:
在这里插入图片描述

对比结果

计算结果:一致

在计算结果上,所有的方法得到的结果都一致。

速 度:torch.add() 胜利

在速度上,我们可以看到 torch.add() 方法显得更加便捷稳定,在深度学习中,计算量很大,如果遇到加法操作,建议还是使用此函数计算。

更多操作~请到官方文档查看。


作者:奥特曼丶毕健旗



pytorch 运算速度

需要 登录 后方可回复, 如果你还没有账号请 注册新账号
相关文章