190. Cython for Performance

1

Basic Cython Speedup

  • Convert a simple Python function to Cython for performance improvement.

example1.pyx

# Cython file (example1.pyx)
def add(int a, int b):
    return a + b

Compilation (Save as setup.py)

from setuptools import setup
from Cython.Build import cythonize

setup(
    ext_modules=cythonize("example1.pyx")
)

Run:

python setup.py build_ext --inplace

Use in Python:

from example1 import add
print(add(10, 20))  # Output: 30

2

Using cdef for Fast Loops

  • cdef declares C variables for faster execution.

example2.pyx

Compile and use it in Python as shown in Example 1.


3

Using nogil for Parallelism

  • nogil allows running code without Python’s Global Interpreter Lock (GIL).

example3.pyx


4

Using Cython with NumPy

  • Speed up NumPy array operations with Cython.

example4.pyx


5

Calling External C Functions

  • Use C functions inside Cython for extreme speedups.

example5.pyx

Compile and call py_sqrt(25.0) from Python.


Last updated