Python有一个标准库disutils,可以用来构建、打包、分发Python工程。
1. 编写Cython程序
# get_angle_cython.pyx
cimport cython
import math
@cython.boundscheck(False)
@cython.wraparound(False)
cdef float _get_angle(float x, float y):
cdef float angle
cdef float tan_yx
angle = 123
if y == 0 :
if x < 0:
angle = 180
else:
angle = 0
if x == 0 :
if y > 0:
angle = 90
else:
angle = 270
else:
tan_yx = abs(y)/abs(x)
if y > 0 and x < 0:
angle = 180 - math.atan(tan_yx)*180/math.pi #90-180
elif y > 0 and x > 0:
angle = math.atan(tan_yx)*180/math.pi #0-90
elif y < 0 and x < 0:
angle = 180 + math.atan(tan_yx)*180/math.pi #180-270
elif y < 0 and x > 0:
angle = 360- math.atan(tan_yx)*180/math.pi #270-360
return angle
def get_angle(x, y):
return _get_angle(x, y)
2. 编写编译配置文件
from distutils.core import setup
from Cython.Build import cythonize
setup(ext_modules=cythonize("get_angle_cython.pyx"))
3. 编译命令
项目所在目录下,命令行输入:
python setup.py build_ext --inplace
–inplace 表示在在当前目录下生成.so文件。
编译之后目录中增加文件:
4. 命令行调用
import get_angle_cython
# 我们看到该so文件直接就被导入了,至于中间的是对应的解释器版本、操作系统等信息
# 可以不用管,甚至你删掉只保留get_angle_cython.so也是可以的。
print(get_angle_cython) # 打印文件路径
print(get_angle_cython.get_angle(100, 200))
5. 对比运行时间
对比Python代码和Cython代码运行时间。
import get_angle
import get_angle_cython
%timeit -n 100 -r 3 get_angle.get_angle(100, 200)
%timeit -n 100 -r 3 get_angle_cython.get_angle(100, 200)