简单数值计算时是否需要把数据转化成tensor格式在gpu上跑呢

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值