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格式