Cython是将Python结合部分C语法的程式语言,与Python的主要差别在于语法中加入了静态类型,使用者可以维持大部分的Python语法,而不需要大幅度调整主要的程式逻辑与演算法。但由于会直接编译为二进制程序,所以性能较Python会有很大提升[5][6]

Quick Facts 实作者, 发行时间 ...
Cython
实作者Robert Bradshaw, Stefan Behnel, et al.
发行时间2007年7月28日,​17年前​(2007-07-28[1]
当前版本
  • 3.0.11-1 (2024年8月5日;稳定版本)[2]
编辑维基数据链接
实作语言Python
操作系统WindowsMacOSLinux
许可证Apache许可证2.0
文件扩展名.pyx, .pxd, .pxi [3]
网站cython.org 编辑维基数据链接
启发语言
C语言PythonPyrex英语Pyrex语言[4]
Close

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

参考资料

参见

外部链接

Wikiwand in your browser!

Seamless Wikipedia browsing. On steroids.

Every time you click a link to Wikipedia, Wiktionary or Wikiquote in your browser's search results, it will show the modern Wikiwand interface.

Wikiwand extension is a five stars, simple, with minimum permission required to keep your browsing private, safe and transparent.