使用numba对Python运算加速的方法

作者:jingxian 时间:2022-05-12 20:30:57 

有时候需要比较大的计算量,这个时候Python的效率就很让人捉急了,此时可以考虑使用numba 进行加速,效果提升明显~

(numba 安装貌似很是繁琐,建议安装Anaconda,里面自带安装好各种常用科学计算库)


from numba import jit

@jit
def t(count=1000):
total = 0
for i in range(int(count)):
 total += i
return total

测试效果:

(关于__wrapped__ 见我的博文: 浅谈解除装饰器作用(python3新增) )


In [17]: %timeit -n 1 t.__wrapped__()
1 loop, best of 3: 52.9 µs per loop

In [18]: %timeit -n 1 t()
The slowest run took 13.00 times longer than the fastest. This could mean that an intermediate result is being cached.
1 loop, best of 3: 395 ns per loop

可以看到使用jit 加速后,即使设置测试一次,实际上还是取了三次的最优值,如果取最坏值(因为最优值可能是缓存下来的),则耗时为395ns * 13 大概是5us 还是比不使用的52.9us 快上大概10倍,

增大计算量可以看到使用numba加速后的效果提升更加明显,


In [19]: %timeit -n 10 t.__wrapped__(1e6)
10 loops, best of 3: 76.2 ms per loop

In [20]: %timeit -n 1 t(1e6)
The slowest run took 8.00 times longer than the fastest. This could mean that an intermediate result is being cached.
1 loop, best of 3: 790 ns per loop

如果减少计算量,可以看到当降到明显小值时,使用加速后的效果(以最差计)与不加速效果差距不大,因此如果涉及到较大计算量不妨使用jit 加速下,何况使用起来这么简便。


%timeit -n 1 t(10)
1 loop, best of 3: 0 ns per loop

%timeit -n 100 t.__wrapped__(10)
100 loops, best of 3: 1.79 µs per loop

%timeit -n 1 t(1)
The slowest run took 17.00 times longer than the fastest. This could mean that an intermediate result is being cached.
1 loop, best of 3: 395 ns per loop

%timeit -n 100 t.__wrapped__(1)
100 loops, best of 3: 671 ns per loop

来源:https://blog.csdn.net/xiaodongxiexie/article/details/79180158

标签:numba,Python,加速
0
投稿

猜你喜欢

  • css表单中textarea域背景图片设置方法

    2008-04-21 13:56:00
  • 分享13款非常有用的jQuery插件

    2011-05-16 19:07:00
  • 2008北京奥运会倒计时js代码

    2008-01-22 18:18:00
  • php获取数组长度的方法(有实例)

    2023-11-20 07:55:28
  • 几个SQL SERVER应用问题解答

    2008-01-01 19:12:00
  • Python多线程与同步机制浅析

    2021-10-31 03:22:51
  • SEM之医疗网站跳出率 逼迫访客跳出网站的六宗罪

    2012-03-05 20:13:36
  • IE7兼容模式与兼容视图

    2010-06-28 18:48:00
  • 按钮表状态还是表动作?

    2009-03-23 18:21:00
  • 解决python中os.listdir()函数读取文件夹下文件的乱序和排序问题

    2022-10-24 05:34:54
  • Python使用pandas和xlsxwriter读写xlsx文件的方法示例

    2022-05-14 00:35:25
  • 读写xml文件的2个小函数

    2007-08-23 12:59:00
  • python request post 列表的方法详解

    2023-10-04 11:46:19
  • python将视频转换为全字符视频

    2023-08-08 21:01:02
  • 浅谈tensorflow 中tf.concat()的使用

    2023-07-21 20:24:08
  • ASP教程:0177:800401f3错误解决

    2008-08-02 12:41:00
  • php基于curl主动推送最新内容给百度收录的方法

    2023-11-22 04:46:44
  • Python中的lambda和apply用法及说明

    2023-08-12 14:56:46
  • 解决Python复杂zip文件的解压问题

    2021-08-11 05:04:09
  • 基于RSA算法在asp中加密与解密对应的函数

    2007-11-07 21:39:00
  • asp之家 网络编程 m.aspxhome.com