0.Cython简介
Cython是具有C数据类型的Python。使用Cython我们可以通过改写部分业务逻辑为C代码并融合到Python中,起到加速代码执行速度的作用。
1.安装Cython
pip install cython
2.编写pyx代码
新建hello_world.pyx
文件,内容如下:
print("Hello World")
from libc.math cimport sin
cpdef double f(double x):
return sin(x*x)
cdef int c_add(int a, int b):
return a + b
def add(a: int, b: int):
return c_add(a, b)
def sub(a: int, b: int):
return a - b
以上有三种定义函数的方式:
- 使用cdef定义配合python的def定义
- 使用cpdef定义函数
- 使用python原生def
示例分别为:
使用cdef定义配合python的def定义
cdef int c_add(int a, int b):
return a + b
def add(a: int, b: int):
return c_add(a, b)
使用cpdef定义函数
cpdef double f(double x):
return sin(x*x)
使用python原生def
def sub(a: int, b: int):
return a - b
3.编写setup.py文件
from distutils.core import setup
from Cython.Build import cythonize
setup(
ext_modules = cythonize("hello_world.pyx",
compiler_directives={'language_level' : "3"})
)
4.生成链接库文件
python setup.py build_ext --inplace
5.测试
(base) ➜ testCython pwd
/root/Projects/CppProjects/testCython
(base) ➜ testCython ls
build hello_world.cpython-38-x86_64-linux-gnu.so setup.py
hello_world.c hello_world.pyx
(base) ➜ testCython python
Python 3.8.3 (default, May 19 2020, 18:47:26)
[GCC 7.3.0] :: Anaconda, Inc. on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import hello_world
Hello World
>>> dir(hello_world)
['__builtins__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', '__test__', 'add', 'f', 'sub']
>>> hello_world.add(3, 4)
7
>>> hello_world.f(3.3)
-0.9944322093031951
>>> hello_world.sub(3.4, 5.5)
-2.1
>>> exit()