Numba使用总结

Numba使用总结_第1张图片

Numba is a just-in-time compiler for Python that works best on code that uses NumPy arrays and functions, and loops.

Numba特点: 

  • Numba是Python的即时编译器,在使用NumPy数组和函数以及循环的代码上效果最佳。就是让你代码运行速度更快;
  • 能让python代码达到C语言的速度;
  • 支持在多个CPU内核上并行计算;
  • 支持 英伟达和 AMD 显卡计算;

注意点:

  • numba在进行第一次编译时需要一定时间,后续操作 对入参同一种类型时,直接读取缓存的编译运行,会非常快! 所以在测试性能时 注意测试方式;
  • 对于循环数较少的情况 和 一般的 numpy代码 优化效果不明显;
  • numba可以通过简单的装饰器实现编译功能;  被编译的函数内部 不能调用其他函数,如果非要调用,则 其他函数也要 加上 numba的编译装饰器;

 

如下简单示例:

import time

from numba import jit

@jit(nopython=True, cache=True)
def other_func():
    return 1


@jit(nopython=True, cache=True)
def go_fast(a):
    x = 0
    for item in range(int(a)):
        x += item
    other_func()
    return x


if __name__ == '__main__':
    # 程序第一次 编译运行,速度有些慢
    one = time.time()
    print(go_fast(50000))
    print(time.time() - one)  # 0.1693580150604248

    # 程序 对 函数相同类型的入参 直接读取缓存中的编辑 运行,速度非常快
    one = time.time()
    print(go_fast(100000))
    print(time.time() - one)  # 1.9073486328125e-06

 

易错注意:

  • 在 被 numba的 jit装饰的 函数 内部 如果要调用其他函数,则其他函数也应该 被 jit装饰,否则报错如下: 

numba.core.errors.TypingError: Failed in nopython mode pipeline (step: nopython frontend)
Untyped global name 'other_func': cannot determine Numba type of

 

相关链接:

https://numba.pydata.org/

 

你可能感兴趣的:(高性能,Numba)