numba加速

  1. 安装
    如果安装过anaconda以及tensorflow等软件,numba可能已经在环境中了。先检查避免重复安装。
    直接利用conda或者pip即可安装:

    $ conda install numba
    $ pip install numba

GPU 安装请注意驱动!!

对于NvidiaGPU需要安装驱动和CUDA(推荐CUDA 8.0 or later)

#官网介绍:conda直接安装cudatoolkit即可,无需安装cuda
$ conda install cudatoolkit
但*pip安装可能需要自行安装cuda,并设置环境变量

NUMBAPRO_CUDA_DRIVER :Path to the CUDA driver shared library file
NUMBAPRO_NVVM :Path to the CUDA libNVVM shared library file
NUMBAPRO_LIBDEVICE :Path to the CUDA libNVVM libdevice directory which contains .bc files

最后使用:numba -s来查看安装情况。

对于numba,如果安装不便的情况下可以使用云服务或者在线notebook来学习, 以及一个GPU的notebook

2.基本使用
Numba主要使用修饰器来对python函数进行编译加速,其中包括了@jit,@vectorize,@cuda.jit等常用修饰器。

import numpy as np

def my_add(a,b):
    return a+b

使用Numpy加速:

from numba import jit
#利用jit编译加速 cpu
@jit
def my_numba_add(x, y):
    return x + y

测试一下函数的表现

#在jupyter 中可以使用%timeit来测试

import time
def test(n):
    a = np.array((n))
    b = np.array((n))
    tic1 = time.time()
    my_add(a,b)
    t1 = time.time()-tic1
    print('python time:',t1)
	
    tic2 = time.time()
    my_numba_add(a,b)
    t2 = time.time()-tic2
    print('Numba time:',t2)
    print('Numba acclerated %f times'%(t1/t2))

#由于计算比较简单,获得的加速比并不大。有兴趣可以加入复杂运算做测试

>>>test(1000)
python time: 2.956390380859375e-05
Numba time: 1.7881393432617188e-05
Numba acclerated 1.653333 times
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值