使用numexpr加快多维数组numpy的算术运算

来源:互联网 发布:高中刷题软件 编辑:程序博客网 时间:2024/06/06 01:39

 numpy是python为了科学计算而开发的支持多维的数组,

据说在numpy的基础上执行算术运算速度很快,

可是和numexpr比起来,要差得远了.

使用numexpr,比numpy的速度要加快数倍,甚至数十倍.

因此在执行大量预算和对大数组进行操作时,一定要使用numexpr.

下面还是看看例子吧,先看看numexpr是如何使用的:

 

numexpr接受字符串表达式即可,分析后立即计算

 

>>> import numpy as np >>> import numexpr as ne  >>> a = np.arange(1e6) >>> b = np.arange(1e6)  >>> ne.evaluate("a + 1")   # 最简单的表达式 array([  1.00000000e+00,   2.00000000e+00,   3.00000000e+00, ...,          9.99998000e+05,   9.99999000e+05,   1.00000000e+06])  >>> ne.evaluate('a*b-4.1*a > 2.5*b')   # 稍微复杂一点的例子array([False, False, False, ...,  True,  True,  True], dtype=bool)


 

 

下面的例子比较了numpy和numexpr运算时间

>>> timeit a**2 + b**2 + 2*a*b 10 loops, best of 3: 21.5 ms per loop  # numexpr w/ 16 threads (default for 8-core, with hyperthreading) >>> timeit ne.evaluate("a**2 + b**2 + 2*a*b") 100 loops, best of 3: 2.14 ms per loop  # 比NumPy快10.0倍>>> ne.set_num_threads(8)  # using just 8 threads >>> timeit ne.evaluate("a**2 + b**2 + 2*a*b") 100 loops, best of 3: 3.15 ms per loop  # 比NumPy快6.8倍>>> ne.set_num_threads(1)  # using just 1 thread >>> timeit ne.evaluate("a**2 + b**2 + 2*a*b") 100 loops, best of 3: 7.58 ms per loop  # 比NumPy快2.8倍


numexpr运算时间不是一般的快,

 

原创粉丝点击