Cython

本页使用了标题或全文手工转换
维基百科,自由的百科全书
Cython
實作者Robert Bradshaw, Stefan Behnel, et al.
发行时间2007年7月28日,​16年前​(2007-07-28[1]
当前版本
  • 3.0.10 (2024年3月30日;穩定版本)[2]
編輯維基數據鏈接
實作語言Python
操作系统WindowsMacOSLinux
許可證Apache许可证2.0
文件扩展名.pyx, .pxd, .pxi [3]
網站cython.org 編輯維基數據鏈接
啟發語言
C語言PythonPyrex英语Pyrex语言[4]

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

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. The Cython Compiler for C-Extensions in Python. EuroPython (28 July 2007: official Cython launch). Vilnius/Lietuva. 2008 [2020-09-12]. (原始内容存档于2016-10-22). 
  2. ^ Release 3.0.10. 2024年3月30日 [2024年4月22日]. 
  3. ^ Cython支援的檔案副檔名格式 – 檔案詞典. [2020-11-23]. (原始内容存档于2022-03-31) (美国英语). 
  4. ^ Related work — Cython 3.0.0a9 documentation. cython.readthedocs.io. [2021-09-03]. (原始内容存档于2021-11-18). 
  5. ^ Cython - an overview — Cython 0.19.1 documentation. Docs.cython.org. [2013-07-21]. (原始内容存档于2013-08-11). 
  6. ^ Smith, Kurt. Cython: A Guide for Python Programmers. O'Reilly Media. 2015 [2019-05-07]. ISBN 978-1-4919-0155-7. (原始内容存档于2019-05-08). 
  7. ^ Mark Lutz. Learning Python, 5th Edition. [2021-09-17]. (原始内容存档于2021-10-08). 
  8. ^ Language Basics — Cython 3.0.0a9 documentation. cython.readthedocs.io. [2021-09-08]. (原始内容存档于2022-02-15). 
  9. ^ Language Basics — Cython 3.0.0a9 documentation. cython.readthedocs.io. [2021-09-08]. (原始内容存档于2022-02-15). 
  10. ^ Interfacing with External C Code — Cython 3.0.0a9 documentation. cython.readthedocs.io. [2021-09-09]. (原始内容存档于2022-04-25). 
  11. ^ Using C++ in Cython — Cython 3.0.0a9 documentation. cython.readthedocs.io. [2021-09-09]. (原始内容存档于2022-02-13). 

參見[编辑]

外部連結[编辑]