本文介绍Python中的超快速计算

Python最为一门比较高级的语言其运行速度自然在大多数时候比不上C这种语言,但其可读性和便捷性还是使这门语言在全球非常的流行。另外,python众多的库使其在各个领域都非常的火热,特别是在数据处理方面。一般情况我们用python进行数据处理时,经常用到的库包括Numpy、Scipy等,实际上这些库已经大大弥补了python运行速度上的短板,但在这里,我们还将介绍一下用python进行的更快的计算库,这个库就是numexpr,其使用也相当简单,直接使用numexpr.evaluate()函数来运行一个表达式即可,举个超级简单的例子

1
2
3
4
import numpy as np
import numexpr as ne
a=np.arange(2000)
r=ne.evaluate('cos(a)')

通过下面的代码我们可以明显看到用四种不同方法来完成同一个任务的时间差异

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
import numpy as np
from timeit import timeit
import numexpr as ne
a=np.arange(1,25000000)
def test1():
global a
r=[np.log(x)*3+np.cos(x)**2 for x in a]
def test2():
global a
r=np.log(a)*3+np.cos(a)**2
def test3():
global a
ne.set_num_threads(1)
f='3*log(a)+cos(a)**2'
r=ne.evaluate(f)
def test4():
global a
ne.set_num_threads(4)
f='3*log(a)+cos(a)**2'
r=ne.evaluate(f)
print timeit('test1()',setup='from __main__ import test1',number=1)
print timeit('test2()',setup='from __main__ import test2',number=1)
print timeit('test3()',setup='from __main__ import test3',number=1)
print timeit('test4()',setup='from __main__ import test4',number=1)
###output
# 84.5878441334
# 2.08765912056
# 0.461308956146
# 0.300596952438

其中set_num_threads函数设置计算的线程数。