深入理解Python 代码优化详解(7)
其他平台上的安装可以参考文档:http://docs.cython.org/src/quickstart/install.html
Cython 代码与 python 不同,必须先编译,编译一般需要经过两个阶段,将 pyx 文件编译为 .c 文件,再将 .c 文件编译为 .so 文件。编译有多种方法:
•通过命令行编译:假设有如下测试代码,使用命令行编译为 .c 文件。
def sum(int a,int b):
print a+b
[root@v5254085f259 test]# cython sum.pyx
[root@v5254085f259 test]# ls
total 76
4 drwxr-xr-x 2 root root 4096 Apr 17 02:45 .
4 drwxr-xr-x 4 root root 4096 Apr 16 22:20 ..
4 -rw-r--r-- 1 root root 35 Apr 17 02:45 1
60 -rw-r--r-- 1 root root 55169 Apr 17 02:45 sum.c
4 -rw-r--r-- 1 root root 35 Apr 17 02:45 sum.pyx
在 linux 上利用 gcc 编译为 .so 文件:
[root@v5254085f259 test]# gcc -shared -pthread -fPIC -fwrapv -O2
-Wall -fno-strict-aliasing -I/usr/include/python2.4 -o sum.so sum.c
[root@v5254085f259 test]# ls
total 96
4 drwxr-xr-x 2 root root 4096 Apr 17 02:47 .
4 drwxr-xr-x 4 root root 4096 Apr 16 22:20 ..
4 -rw-r--r-- 1 root root 35 Apr 17 02:45 1
60 -rw-r--r-- 1 root root 55169 Apr 17 02:45 sum.c
4 -rw-r--r-- 1 root root 35 Apr 17 02:45 sum.pyx
20 -rwxr-xr-x 1 root root 20307 Apr 17 02:47 sum.so
使用 distutils 编译
建立一个 setup.py 的脚本:
from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext
ext_modules = [Extension("sum", ["sum.pyx"])]
setup(
name = 'sum app',
cmdclass = {'build_ext': build_ext},
ext_modules = ext_modules
)
[root@v5254085f259 test]# python setup.py build_ext --inplace
running build_ext
cythoning sum.pyx to sum.c
building 'sum' extension
gcc -pthread -fno-strict-aliasing -fPIC -g -O2 -DNDEBUG -g -fwrapv -O3
-Wall -Wstrict-prototypes -fPIC -I/opt/ActivePython-2.7/include/python2.7
-c sum.c -o build/temp.linux-x86_64-2.7/sum.o
gcc -pthread -shared build/temp.linux-x86_64-2.7/sum.o
-o /root/cpython/test/sum.so
编译完成之后可以导入到 python 中使用:
[root@v5254085f259 test]# python
ActivePython 2.7.2.5 (ActiveState Software Inc.) based on
Python 2.7.2 (default, Jun 24 2011, 11:24:26)
[GCC 4.0.2 20051125 (Red Hat 4.0.2-8)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import pyximport; pyximport.install()
>>> import sum
>>> sum.sum(1,3)
下面来进行一个简单的性能比较:
清单 9. Cython 测试代码