知识是一种生活方式

numba库介绍

numba库介绍

1.介绍 GitHub链接

numba是python的即时编译器,当调用python函数时,全部或部分代码会被替换为机器码执行!由Anaconda公司赞助。numba可以加速计算负载比较大的python函数(例如循环),主要针对浮点数,支持numpy库。

2.安装

Ubuntu18

apt install llvm pip3 install numba

使用anaconda

conda install numba

3.基本使用

示例

from numba import jit import numpy as np

x= np.arange(100).reshape(10,10)

@jit(nopython=True) def go_fast(a): trace=0 for i in range(a.shape[0]): trace += np.tanh(a[i,i]) return a+trace

print(go_fast(x))

@jit 表示尽可能加速,但对于无法加速的函数和类型仍使用python

@njit 表示全部使用加速,可能会变得更慢,等同于@jit(nopython=True)

需要注意的是numba不理解pandas的DataFrame格式。

4.其他装饰器

@vectorize 生成numpy的ufunc,支持所有ufunc方法,可以支持配置精度。 ’’' @vectorize([int32(int32, int32), int64(int64, int64), float32(float32, float32), float64(float64, float64)]) def f(x, y): return x + y ’’' https://numba.pydata.org/numba-doc/latest/user/vectorize.html#vectorize

@guvectorize 生成numpy的广义ufunc,可以直接定义数组。 https://numba.pydata.org/numba-doc/latest/user/vectorize.html#guvectorize

@stencil 将函数声明为类似stencil类型操作的核函数。

@jitclass 基于jit类。

@cfunc 声明一个函数用作本地回调。

@overload 注册自己的函数实现,以便在nopython中使用。

其他装饰器参数: parallel=True 启用函数的自动并行化。

fastmath=True 启用函数的快速数学行为。

cffi 在nopython模式下支持调用cffi函数。

ctypes 在nopython模式下支持调用ctypes包装函数。

主要参考链接

← 返回文章列表 回到首页