Cython

Cython是结合了PythonC的语法的一种语言,可以简单的认为就是给Python加上了静态类型后的语法,用户可以维持大部分的Python语法,而不需要大幅度调整主要的程序逻辑与算法。但由于会直接编译为二进制进程,所以性能较Python会有很大提升。[5][6]

Cython
实作者Robert Bradshaw, Stefan Behnel, et al.
2007年7月28日2007-07-28[1]
当前版本
  • 3.0.9 (2024年3月5日;稳定版本)[2]
实作语言Python
操作系统WindowsMacOSLinux
许可证Apache许可证2.0
文档扩展名.pyx, .pxd, .pxi [3]
网站
启发语言
C语言PythonPyrex[4]

Cython典型的运用于编写Python扩展模块,以取得较高的运行性能。Cython将原代码转译成C或C++语法后,自动包装上函数调用界面生成.pyd(或 .so ,因操作系统而异)后缀的二进位档,即可当成普通的Python函数库。其性能一般逊于原生的C/C++函数库,但由于Cython语法的易用性可以缩短开发时间。Cython也可以用于将C/C++代码封装为Python函数库。

Cython 文档的扩展名为 .pyx。 在最基本的情况下,Cython 代码看起来与 Python 代码完全一样。 然而,虽然标准 Python 是动态类型的,但在 Cython 中,可以选择提供类型,从而提高性能,并允许在可能的情况下将循环转换为 C 循环。 [7]

语法

定义变量

可以使用关键字cdef定义变量[8]

cdef int a = 1

定义函数

可以使用关键字def、cdef、或cpdef定义函数。

cdef int f(int x):
    return x + 1

使用关键字cdef定义的函数,会被Cython编译成C语言,所以速度较快,但无法被Python使用;只有使用def或cpdef定义的函数可以在Python中使用。[9]

定义结构

cdef struct x:
  int y
  float z

使用 C 标头档

cdef extern from "stdio.h":
    int puts(const char*)

[10]

如果要使用C标准库中的函数,也可以这样写:

from libc.stdio cimport puts

使用 C++ 标头档

#distutils: language = c++
cdef extern from "<vector>" namespace "std":
    cdef cppclass vector[T]:
        vector()
        void push_back(T&)
        T& operator[](int)
        T& at(int)

[11]

或:

#distutils: language = c++
from libcpp.vector cimport vector

编译

cythonize -3 -i example.pyx

参考数据

  1. Behnel, Stefan. . EuroPython (28 July 2007: official Cython launch). Vilnius/Lietuva. 2008 [2020-09-12]. (原始内容存档于2016-10-22).
  2. . 2024年3月5日 [2024年3月22日].
  3. . [2020-11-23]. (原始内容存档于2022-03-31) (美国英语).
  4. . cython.readthedocs.io. [2021-09-03]. (原始内容存档于2021-11-18).
  5. . Docs.cython.org. [2013-07-21]. (原始内容存档于2013-08-11).
  6. Smith, Kurt. . O'Reilly Media. 2015 [2019-05-07]. ISBN 978-1-4919-0155-7. (原始内容存档于2019-05-08).
  7. Mark Lutz. . [2021-09-17]. (原始内容存档于2021-10-08).
  8. . cython.readthedocs.io. [2021-09-08]. (原始内容存档于2022-02-15).
  9. . cython.readthedocs.io. [2021-09-08]. (原始内容存档于2022-02-15).
  10. . cython.readthedocs.io. [2021-09-09]. (原始内容存档于2022-04-25).
  11. . cython.readthedocs.io. [2021-09-09]. (原始内容存档于2022-02-13).

参见

外部链接

This article is issued from Wikipedia. The text is licensed under Creative Commons - Attribution - Sharealike. Additional terms may apply for the media files.