这个是最直接的加法。
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() 方法显得更加便捷稳定,在深度学习中,计算量很大,如果遇到加法操作,建议还是使用此函数计算。
更多操作~请到官方文档查看。