1,使用tensor,USE_CUDA=True
import torch,time,math
USE_CUDA=torch.cuda.is_available()
USE_CUDA=True
def get_location(elevation,azimuth):
elevation_tensor=torch.tensor(elevation)
azimuth_tensor=torch.tensor(azimuth)
if USE_CUDA:
elevation_tensor.cuda()
azimuth_tensor.cuda()
x_tensor = torch.sin(torch.pi * elevation_tensor / 180) * torch.cos( torch.pi * azimuth_tensor / 180)
y_tensor = torch.sin(torch.pi * elevation_tensor / 180) * torch.sin( torch.pi * azimuth_tensor / 180)
z_tensor = torch.cos(torch.pi * elevation_tensor / 180)
x=x_tensor.item()
y=y_tensor.item()
z=z_tensor.item()
print(x,y,z)
return x,y,z
start = time.time()
get_location(0,90)
end = time.time()
print(end-start)
结果
-0.0 0.0 1.0
3.648632049560547
2,使用tensor,USE_CUDA=False
import torch,time,math
USE_CUDA=torch.cuda.is_available()
USE_CUDA=False
def get_location(elevation,azimuth):
elevation_tensor=torch.tensor(elevation)
azimuth_tensor=torch.tensor(azimuth)
if USE_CUDA:
elevation_tensor.cuda()
azimuth_tensor.cuda()
x_tensor = torch.sin(torch.pi * elevation_tensor / 180) * torch.cos( torch.pi * azimuth_tensor / 180)
y_tensor = torch.sin(torch.pi * elevation_tensor / 180) * torch.sin( torch.pi * azimuth_tensor / 180)
z_tensor = torch.cos(torch.pi * elevation_tensor / 180)
x=x_tensor.item()
y=y_tensor.item()
z=z_tensor.item()
print(x,y,z)
return x,y,z
start = time.time()
get_location(0,90)
end = time.time()
print(end-start)
结果
-0.0 0.0 1.0
0.00550079345703125
3,math模块完成运算
import torch,time,math
elevation=0
azimuth=90
start = time.time()
x1 = math.sin(math.pi * elevation / 180) * math.cos(math.pi * azimuth / 180)
y1 = math.sin(math.pi * elevation / 180) * math.sin(math.pi * azimuth / 180)
z1 = math.cos(math.pi * elevation / 180)
print(x1,y1,z1)
end = time.time()
print(end-start)
结果
0.0 0.0 1.0
4.124641418457031e-05
4,使用函数调用
import torch,time,math
def get_location1(elevation,azimuth):
x1 = math.sin(math.pi * elevation / 180) * math.cos(math.pi * azimuth / 180)
y1 = math.sin(math.pi * elevation / 180) * math.sin(math.pi * azimuth / 180)
z1 = math.cos(math.pi * elevation / 180)
print(x1,y1,z1)
return x1,y1,z1
start = time.time()
get_location1(0,90)
end = time.time()
print(end-start)
结果
0.0 0.0 1.0
4.076957702636719e-05
综上,在数值计算的时候没必要把数据转换成tensor格式
本文对比了使用Tensor(CUDA启用和禁用)、math模块以及直接函数调用进行数值计算的效率。结果显示,在不使用GPU的情况下,直接使用math模块和函数调用的效率更高,且差距极小。对于简单计算,没有必要将数据转换为Tensor格式。
1686

被折叠的 条评论
为什么被折叠?



