Cython
Cython是结合了Python和C的语法的一种语言,可以简单的认为就是给Python加上了静态类型后的语法,用户可以维持大部分的Python语法,而不需要大幅度调整主要的程序逻辑与算法。但由于会直接编译为二进制进程,所以性能较Python会有很大提升。[5][6]
![]() | |
实作者 | Robert Bradshaw, Stefan Behnel, et al. |
---|---|
2007年7月28日[1] | |
当前版本 |
|
实作语言 | Python |
操作系统 | Windows、MacOS、Linux |
许可证 | Apache许可证2.0 |
文档扩展名 | .pyx, .pxd, .pxi [3] |
网站 | |
启发语言 | |
C语言、Python、Pyrex[4] |
Cython典型的运用于编写Python扩展模块,以取得较高的运行性能。Cython将原代码转译成C或C++语法后,自动包装上函数调用界面生成.pyd(或 .so ,因操作系统而异)后缀的二进位档,即可当成普通的Python函数库。其性能一般逊于原生的C/C++函数库,但由于Cython语法的易用性可以缩短开发时间。Cython也可以用于将C/C++代码封装为Python函数库。
Cython 文档的扩展名为 .pyx。 在最基本的情况下,Cython 代码看起来与 Python 代码完全一样。 然而,虽然标准 Python 是动态类型的,但在 Cython 中,可以选择提供类型,从而提高性能,并允许在可能的情况下将循环转换为 C 循环。 [7]
语法
定义函数
可以使用关键字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*)
如果要使用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)
或:
#distutils: language = c++
from libcpp.vector cimport vector
编译
cythonize -3 -i example.pyx
参考数据
- Behnel, Stefan. . EuroPython (28 July 2007: official Cython launch). Vilnius/Lietuva. 2008 [2020-09-12]. (原始内容存档于2016-10-22).
- . 2024年3月5日 [2024年3月22日].
- . [2020-11-23]. (原始内容存档于2022-03-31) (美国英语).
- . cython.readthedocs.io. [2021-09-03]. (原始内容存档于2021-11-18).
- . Docs.cython.org. [2013-07-21]. (原始内容存档于2013-08-11).
- Smith, Kurt. . O'Reilly Media. 2015 [2019-05-07]. ISBN 978-1-4919-0155-7. (原始内容存档于2019-05-08).
- Mark Lutz. . [2021-09-17]. (原始内容存档于2021-10-08).
- . cython.readthedocs.io. [2021-09-08]. (原始内容存档于2022-02-15).
- . cython.readthedocs.io. [2021-09-08]. (原始内容存档于2022-02-15).
- . cython.readthedocs.io. [2021-09-09]. (原始内容存档于2022-04-25).
- . 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.