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()

6.参考

  1. Cython 基本用法 - 知乎
  2. Cython教程与代码之——Cython_tutorial之(5到完结) - 知乎
  3. python - 如何在Cython的setup.py中指定Python 3源? - IT工具网
  4. Tutorials - 基础教程 - 《Cython 3.0 中文文档》 - 书栈网 · BookStack
  5. 《Cython系列》1. Cython 是什么?为什么要有 Cython?为什么我们要用 Cython? - 古明地盆 - 博客园

评论




博客内容遵循 署名-非商业性使用-相同方式共享 4.0 国际 (CC BY-NC-SA 4.0) 协议

本站使用 Volantis 作为主题,总访问量为
载入天数...载入时分秒...
冀ICP备20001334号