190. Cython for Performance
1
Basic Cython Speedup
Convert a simple Python function to Cython for performance improvement.
example1.pyx
Copy
# Cython file (example1.pyx)
def add(int a, int b):
return a + bCompilation (Save as setup.py)
Copy
from setuptools import setup
from Cython.Build import cythonize
setup(
ext_modules=cythonize("example1.pyx")
)Run:
Copy
python setup.py build_ext --inplaceUse in Python:
Copy
2
Using cdef for Fast Loops
cdefdeclares C variables for faster execution.
example2.pyx
Copy
Compile and use it in Python as shown in Example 1.
3
Using nogil for Parallelism
nogilallows running code without Python’s Global Interpreter Lock (GIL).
example3.pyx
Copy
4
Using Cython with NumPy
Speed up NumPy array operations with Cython.
example4.pyx
Copy
5
Calling External C Functions
Use C functions inside Cython for extreme speedups.
example5.pyx
Copy
Compile and call py_sqrt(25.0) from Python.
Last updated