
Image by Author | Perplexity
Introduction
Python is celebrated for its simplicity and extensive ecosystem of libraries, making it a top choice for data science and statistical analysis. However, for computationally intensive tasks, pure Python can sometimes be slow. This is because Python is an interpreted, dynamically-typed language. When performance is critical, data scientists often turn to lower-level languages like C or C++. But what if you could get the speed of C without leaving the comfort of the Python environment?
This is where Cython comes in. Cython is a superset of Python that supports static type declarations, which Cython translates into highly optimized C code, and which makes writing C extensions for Python as easy as Python itself. By optimizing critical parts of your statistical algorithms with Cython, you can achieve significant speed improvements with minimal changes to your existing code.
Creating a Baseline with Pure Python
To understand the performance benefits of Cython, let’s start with a pure Python function that performs a common statistical computation. We’ll create a function to calculate the pairwise Euclidean distance between all points in a synthetic dataset. This task is computationally expensive, as it involves nested loops and repeated calculations, making it an ideal candidate for optimization.
Here’s our baseline Python implementation using NumPy for array operations.
import numpy as np
def pairwise_python(X):
num_samples = X.shape[0]
distances = np.zeros((num_samples, num_samples))
for i in range(num_samples):
for j in range(num_samples):
distances[i, j] = np.sqrt(np.sum((X[i, :] - X[j, :])**2))
return distances
We will time this function to establish a performance baseline before introducing Cython.
Optimizing with Cython
Now, let’s convert our Python function into a Cython module. The process involves saving the code with a .pyx extension and adding static type declarations. By specifying the types of our variables (e.g. as C doubles or integers), Cython can bypass Python’s slower dynamic-typing and generate optimized C code.
Save the following code as pairwise_cython.pyx. Notice the use of cdef to declare typed variables. Also note the use of 2 decorators: @cython.boundscheck(False) is used to disable bounds checking for a small additional speed boost; @cython.wraparound(False) is used to disable negative array indexing, providing an additional small speed boost.
These wrappers are performance optimizations that make the Cython code run faster by removing safety checks that aren’t needed in this specific case. They should only be used when you’re certain your code won’t violate these conditions (no out-of-bounds access and no negative indices).
import numpy as np
cimport numpy as np
import cython
@cython.boundscheck(False)
@cython.wraparound(False)
def pairwise_cython(np.ndarray[double, ndim=2] X):
cdef int num_samples = X.shape[0]
cdef np.ndarray[double, ndim=2] distances = np.zeros((num_samples, num_samples))
cdef int i, j
for i in range(num_samples):
for j in range(num_samples):
distances[i, j] = np.sqrt(np.sum((X[i] - X[j])**2))
return distances
Compiling the Cython Module
Before we can use our Cython function, we need to compile it into a Python extension module. This is done using a setup.py script. Create a file named setup.py in the same directory with the following content:
from distutils.core import setup
from Cython.Build import cythonize
import numpy
setup(
ext_modules=cythonize("pairwise_cython.pyx"),
include_dirs=[numpy.get_include()]
)
Make sure you have installed Cython before moving any further ahead. The easiest way to do so is by using pip:
pip install Cython
You will also want to ensure that yuo have a C compiler installed (such as gcc, on Linux).
Run the following command in your terminal to build the module:
python setup.py build_ext --inplace
This command generates a compiled module (e.g. pairwise_cython.so on Linux, or similar) that you can import directly into your Python scripts.
Comparing Performance
With both the pure Python and Cython versions ready, we can now compare their performance. We’ll generate a random dataset and use Python’s timeit module to measure the execution time of each function.
import timeit
import numpy as np
from pairwise_cython import pairwise_cython
# Create a sample dataset
X = np.random.rand(500, 3)
# Time the pure Python version
python_time = timeit.timeit('pairwise_python(X)',
setup='from __main__ import pairwise_python, X',
number=10)
# Time the Cython version
cython_time = timeit.timeit('pairwise_cython(X)',
setup='from __main__ import pairwise_cython, X',
number=10)
print(f"Pure Python time: {python_time:.4f} seconds")
print(f"Cython time: {cython_time:.4f} seconds")
print(f"Speedup: {python_time / cython_time:.2f}x")
Pure Python time: 6.0930 seconds Cython time: 5.8107 seconds Speedup: 1.05x
While the speedup was modest in this particular case, please keep in mind that this is just our first step. In typical scenarios, you can expect Cython implementations to be several times faster, and in some cases, orders of magnitude faster than the pure Python code.
Wrapping Up
Cython provides a powerful and accessible way to accelerate statistical computations in Python. By adding simple type annotations to your code, you can leverage the performance of C while retaining the high-level, expressive syntax of Python. For data scientists dealing with large datasets or complex algorithms, Cython is an invaluable tool for optimizing performance bottlenecks and making your analytical workflows more efficient.
