一、背景

写了个算法 需要多次计算两个字符串的编辑距离。这部分耗时比较多,想要进行优化。编辑距离代码见最后的附录。编辑距离本质上是双层for loop,而且是有依赖关系的for loop,因此无法并行。然后发现 numba ,介绍如下:
Numba is a just-in-time compiler for Python that works best on code that uses NumPy arrays and functions, and loops. The most common way to use Numba is through its collection of decorators that can be applied to your functions to instruct Numba to compile them. When a call is made to a Numba decorated function it is compiled to machine code “just-in-time” for execution and all or part of your code can subsequently run at native machine code speed!

本文主要介绍 nopython模式和 parallel模式

二、用法及其说明

2.1 @numba.njit()

用法非常简单,在函数上面使用装饰器

import numba@numba.jit(nopython=True) # 等价于 @numba.njit()
def editing_distance(word1: str, word2: str):''''''pass

nopython=True 意味着numba对装饰器 装饰的函数进行编译成机器码,完全不使用python 解释器。 注意

  1. 使用nopython=True 意味着着最佳的性能
  2. 如果nopython=True 失败,可以切换另外一个模式object 。这个模式会把可以把可编译为机器码的for loop 编译,无法成功编译的则使用python 解释器运行。这个加速效果就会比较差,建议如果发现nopython=True 的跑不通,就尽量去改变代码,让代码变得更贴近pure python,进而让代码跑通。
  3. 使用numba加速的函数,第一次被调用的时候会进行初次编译,这个时间会比较久。计算耗时的时候不应该被记入。第一次之后的执行都会感受到numba的加速
  4. numba 不会对所有的for loop都有明显的加速效果。具体的对于什么for loop有比较好的加速效果需要看代码。一般来说对于 pure python的数据结构和numpy 都会有比较好的加速效果

2.2 @numba.njit(parallel=True)

对并行的代码进行加速。
level 1 : 原始

def ident_parallel(x):return np.cos(x) ** 2 + np.sin(x) ** 2

level 2 : @numba.njit() 把python编译成机器码,加速 for loop

@numba.njit()
def ident_parallel(x):return np.cos(x) ** 2 + np.sin(x) ** 2

level 3 : @numba.njit(parallel=True) 把python编译成机器码加速for loop ,且同时利用并行进行优化

@numba.njit(parallel=True)
def ident_parallel(x):return np.cos(x) ** 2 + np.sin(x) ** 2

测试函数如下

if __name__=='__main__':a = np.zeros((20000, 20000))a_time = time.time()ident_parallel(a)b_time = time.time()print(f' consuming time is {b_time-a_time}')

耗时统计如下

level 1 约 4.3 s
level 2 约 0.9 s
level 3 约 0.29 s

可以依次看到 njit 的速度提升以及 njit+parallel 的速度提升

三、numba为什么快

https://numba.readthedocs.io/en/stable/user/5minguide.html#how-does-numba-work

Numba reads the Python bytecode for a decorated function and combines this with information about the types of the input arguments to the function. It analyzes and optimizes your code, and finally uses the LLVM compiler library to generate a machine code version of your function, tailored to your CPU capabilities. This compiled version is then used every time your function is called.

提前获取Python的输入参数类型,把Python的字节码转化成机器码,转化的过程有针对性的优化。每次使用这个函数的时候 直接使用的是机器码,而无需重新编译

附录

编辑距离

def editing_distance(word1: str, word2: str):'''两个字符串的编辑距离. '''if len(word1)==0:return len(word2)if len(word2)==0:return len(word1)size1 = len(word1)size2 = len(word2)last = 0tmp = list(range(size2 + 1))value = Nonefor i in range(size1):tmp[0] = i + 1last = ifor j in range(size2):if word1[i] == word2[j]:value = lastelse:value = 1 + min(last, tmp[j], tmp[j + 1])last = tmp[j+1]tmp[j+1] = valuereturn value

python: numba 加速python的 for loop相关推荐

  1. python sum函数numpy_如何用numba加速python?

    我把写好的markdown导入进来,但是没想到知乎的排版如此感人.如果对知乎排版不满想要看高清清爽版,请移步微信公众号原文 如何用numba加速python?同时欢迎关注 前言 说道现在最流行的语言, ...

  2. python numba_如何用numba加速python?

    我把写好的markdown导入进来,但是没想到知乎的排版如此感人.如果对知乎排版不满想要看高清清爽版,请移步微信公众号原文 如何用numba加速python?同时欢迎关注 前言 说道现在最流行的语言, ...

  3. Numba加速Python教程

    Numba加速Python代码教程 Numba介绍 Numba可运行环境 Numba安装 Numba教程 Numba简单示例 Numba装饰器 Numba理解 什么是nopython模式? 如何衡量N ...

  4. linux下载python numba,安装numba和使用numba加速python程序

    这是从其他博客粘贴过来,备份的.原文在:http://www.cnblogs.com/freeweb/p/6652607.html 使用Cython来加速python程序的运行速度,但是相对来说程序改 ...

  5. python打包无法识别numba_用 Numba 加速 Python 代码

    原文出自微信公众号:Python那些事 一.介绍 pip install numba Numba 是 python 的即时(Just-in-time)编译器,即当你调用 python 函数时,你的全部 ...

  6. numba加速python代码

    前言 说道现在最流行的语言,就不得不提python.可是python虽然容易上手,但速度却有点感人.如何用简单的方法让python加速到近乎可以媲美C的速度呢?今天来就来谈谈numba这个宝贝.对你没 ...

  7. 用 Numba 加速 Python 代码

    1.介绍 Numba 是 python 的即时(Just-in-time)编译器,即当您调用 python 函数时,您的全部或部分代码就会被转换为"即时"执行的机器码,它将以您的本 ...

  8. 使用numba加速python

    文章目录 一.numba的安装 二.代码 三.相关问题 1.njit 2.数据类型 3.返回值 4.吐槽 一.numba的安装 numba是一个高性能的python编译器,所装饰的函数将会通过LLVM ...

  9. Python Numba实现GPU加速

    Python与GPU Python作为解释型语言,.py文件一般是没法直接用GPU加速的,关于Python与GPU的结合点,以及GPU.CPU.CUDA.多核.并行.机器码-等底层实现,参考: < ...

最新文章

  1. 高效的 JavaScript
  2. 滚动条插件nicescroll的使用
  3. 人工智能训练机器人的服务器,人工智能系统教会机器人如何在荒野中行走
  4. 代码抽象_如何通过抽象使代码更具可读性
  5. 实操案例:字符串哈希表操作
  6. vc6开发一个抓包软件_开发一个软件要多少钱?app软件开发的费用
  7. 年底活动那么多!!给你一组超牛的促销标签素材!!!
  8. 使用 ReSharper对.NET解决方案进行全面重构
  9. Python 列表应用之“简易好友管理系统”
  10. 2022-04-行为经济学-光华管理学院-孟涓涓
  11. 怎么给视频打马赛克?视频剪辑时快速添加马赛克的方法
  12. 菜鸟阿鑫对于一堆数组的总结以及理解
  13. VMware虚拟机 centos8 解决全屏问题
  14. 在支付宝中开通信用卡快捷支付
  15. 抽奖活动啦!5本SpringMVC+MyBatis相关、3本Android Studio相关、6本Kafka相关
  16. JavaScript的三级联动
  17. antD布局不能占满屏幕问题
  18. CorelDRAW VBA - 读取XML文件,根据内容批量创建图形
  19. jxl导出excel(合并单元格)
  20. VBA-EXCEL:控制WORD指定位置,插入图片并调整在大小,高低,环绕

热门文章

  1. MySQL之数据表(数据库的创建与删除、数据表的创建与删除)
  2. 轻松理解前后端分离(通俗易懂)
  3. Jplayer插件使用浅析
  4. 个人认为最佳模板制作方案
  5. Linux -- lvm逻辑卷管理和RAID
  6. Python 之 处理 Excel 数据(5) —— 更新指定单元格的值
  7. 通俗理解什么是ngram
  8. c语言44种运算符,C语言运算符优先级
  9. CSS再学习(如何设置背景图片透明,弹性盒子,盒子阴影)+HTML冷门知识
  10. JAVA ftps设置_Java使用JSCH实现对FTPS服务器文件操作