關於 Cython 程式語言的事實
Cython 是一種程式語言,它是 Python 的超集,可以編譯成 C 程式碼以提高效能。Cython 的開發是為了提高執行速度,使程式碼比 Python 更快。在本文中,我們將瞭解一些關於 Cython 程式語言的有趣事實。
Cython 可用於加速 Python 程式碼
顧名思義,Cython 是類似 Python 的程式碼,可以轉換為 C 程式碼以實現更快、更有效的執行速度。開發人員可以使用 Python 編寫程式碼,然後將其編譯成 C 程式碼,從而使語言速度更快。
示例
在下面的示例中,Cython 程式碼與 Python 程式碼幾乎相同,但cpdef關鍵字告訴 Cython 將函式編譯成 C 程式碼。這可以顯著提高速度,尤其是在計算密集型任務中。
# Python code def fibonacci(n): if n <= 1: return n return fibonacci(n-1) + fibonacci(n-2) print(fibonacci(3)) # Cython code cpdef int fibonacci(int n): if n <= 1: return n return fibonacci(n-1) + fibonacci(n-2) print(fibonacci(3))
輸出
2 2
Cython 支援靜態型別。
Cython 支援靜態型別,這意味著變數型別應在編譯時宣告,這與 Python 不同,在 Python 中變數的型別可以在執行時更改。靜態型別導致更快的程式碼執行。
示例
在下面的示例中,Python 程式碼未指定變數a和b的型別,而在 Python 程式碼中,變數 a 和 b 已被初始化為整數資料型別。
# Python code def add(a, b): return a + b print(add(2,3)) # Cython code with static typing cpdef int add(int a, int b): return a + b print(add(2,3))
輸出
5 5
Cython 可以與 C 程式碼互動
Cython 旨在與 C 程式碼相容,便於與現有的 C 庫整合。Cython 程式碼可以編譯成 C 程式碼,然後可以將其與 C 程式碼連結以建立單個可執行檔案。
示例
在下面的示例中,hello_world() 函式是用 C 程式碼編寫的,並在 Cython 程式碼中宣告為外部函式。編寫的 greet() 函式呼叫 hellow_world() 函式以列印“Hellow_world”。
# C code #include <stdio.h> void hello_world() { printf("Hello, world!\n"); } # Cython code cdef extern void hello_world() def greet(): hello_world()
輸出
Hello, world!
Cython 可以編譯成 C 程式碼
示例
下面的程式碼是用 Cython 編寫的,其中變數宣告為整數資料型別,返回型別也是整數。可以使用cython包中的cythonize實用程式將下面的程式碼編譯成 C 程式碼。
# Python code def add_numbers(a, b): return a + b print(add(2,3)) # Cython code with static typing cpdef int add_numbers(int a, int b): return a + b print(add(2,3))
輸出
5 5
# setup.py file for compiling Cython code from distutils.core import setup from Cython.Build import cythonize setup( ext_modules = cythonize("example.pyx") )
執行 python setup.py build_ext --in-place 後,將生成一個已編譯的 C 模組,與原始 Cython 程式碼一起。
# Example output (after compiling and importing the Cython module) >>> from example import add_numbers >>> add_numbers(2, 3)
輸出
5
結論
在本文中,我們討論了關於 Cython 程式語言的一些事實。Cython 程式語言是一種類似 Python 的語言,它被編譯成 C 程式碼以實現更快的執行速度。我們解釋瞭如何使用 Cython 加速 Python 程式碼以及它如何與 C 程式碼互動。Cython 被編譯成 C 程式碼以實現更快的執行。