Pytorch:比较CPU和GPU的运算速度

在跑神经网络的时候,GPU的作用是很明显的。下面比较一下CPU跑和GPU跑的区别:

先用CPU跑:

import torch
import time

for i in range(1,10):
    start_time = time.time() #返回当前语句运行时的时间点(单位秒)。
    a = torch.rand(i*100, 1000, 1000)   #生成i*100个的10001000矩阵组成的张量,每个元素为0-1之间的随机值。
    a = torch.mul(a,a)
    Cul_end_time = time.time() - start_time
    print(Cul_end_time)

输出:

0.441303014755249
0.8848202228546143
1.287822961807251
1.7319905757904053
2.177103281021118
2.555281162261963
2.9773526191711426
3.3875885009765625
3.9365322589874268

Process finished with exit code 0

再用GPU跑,代码如下:

import torch
import time

for i in range(1,10):
    start_time = time.time() #return current time in second.
    a = torch.rand(i*100, 1000, 1000)
    
    a = a.cuda()   #和上面的区别是,a.cuda()把张量a转到GPU中,下面的运算就在GPU进行了
    
    a = torch.mul(a,a)
    Cul_end_time = time.time() - start_time
    print(Cul_end_time)

输出:

526.2110984325409
1.0246520042419434
1.4614639282226562
1.8706181049346924
2.5586912631988525
3.071241617202759
3.5114991664886475
3.9417364597320557
4.653223752975464

Process finished with exit code 0

第一次运算的时候花了526秒,近9分钟,是在等数据加载到显卡中。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值