Cython 对Python优化方式在速度上的差异比较
Cython 的介绍
- Cython 是一个Python解释器
- 可以在不更改Python代码的情况下,编译Python代码,可以将动态的Python代码,生成C代码,有时会快几个数量级
- Cython 中的类型声明使源代码冗长,可读性差,所有要确实有必须要优化的的情况下使用
Cython 对不用使用对在速度上的比较
- 准备:
- 使用原生的 Python:primes_py.py
def primes(nb_primes): p = [] n = 2 while len(p) < nb_primes: # Is n prime? for i in p: if n % i == 0: break # If no break occurred in the loop else: p.append(n) n += 1 return p
2. 使用 Cython 对Python进行编译:拷贝 primes_py.py,重命令:primes_c.py
from distutils.core import setup from Cython.Build import cythonize setup( ext_modules=cythonize( ["primes_c.py"], annotate=True) )
3. 使用 pyx 编写:primes_pyx.pyx
def primes(int nb_primes): cdef int n, i, len_p cdef int p[1000] if nb_primes > 1000: nb_primes = 1000 len_p = 0 # The current number of elements in p. n = 2 while len_p < nb_primes: # Is n prime? for i in p[:len_p]: if n % i == 0: break # If no break occurred in the loop, we have a prime. else: p[len_p] = n len_p += 1 n += 1 # Let's return the result in a python list: result_as_list = [prime for prime in p[:len_p]] return result_as_list
编写, setup.py
from distutils.core import setup from Cython.Build import cythonize setup( ext_modules=cythonize( ["primes_pyx.pyx"], annotate=True) )
- 比较:
(venv) yangshujun@yangshujundeMacBook-Pro cython_build % python -m timeit -s 'from primes_py import primes as primes' 'primes(1000)' 10 loops, best of 5: 30.7 msec per loop (venv) yangshujun@yangshujundeMacBook-Pro cython_build % python -m timeit -s 'from primes_c import primes' 'primes(1000)' 20 loops, best of 5: 14.5 msec per loop (venv) yangshujun@yangshujundeMacBook-Pro cython_build % python -m timeit -s 'from primes_pyx import primes' 'primes(1000)' 200 loops, best of 5: 1.49 msec per loop
primes_py 的Cythonize版本,比纯Python快了2倍,而不需要更改任意一行代码, Cython版本(primes_pyx)比纯Python版快了。。。