Lesson 40 of 41
Performance Optimization: Vectorization, cProfile & Memory Profiling
Overview & Learning Objectives
As datasets expand from thousands to tens of millions of records, naive Python code with `for` loops, `.iterrows()`, and non-vectorized custom functions causes scripts to slow to an unworkable crawl. High-performance data analytics demands an understanding of CPython performance bottlenecks, using `cProfile` and `line_profiler` to identify slow lines of code, replacing row-by-row iteration with SIMD vectorized operations, and utilizing JIT (Just-In-Time) compilation via Numba for custom numerical calculations.
- Benchmark and profile code bottlenecks using `cProfile`, `%timeit`, and `line_profiler`.
- Refactor slow iterative loops (`for`, `.iterrows()`, `.apply()`) into C-speed vectorized NumPy/Pandas operations.
- Deploy Numba JIT compilation (`@njit`) to achieve pure C/C++ execution speeds on custom numerical loops.
Industry Standard
Standard: Algorithmic trading desks at Citadel and Jane Street forbid row-wise Python iteration in execution pipelines, mandating vectorized NumPy routines or Cython/Numba kernels to meet latency SLAs.
Real-World Example: ScoopCraft 10-Million Order Haversine Distance Optimization
ScoopCraft calculates exact delivery route distances between dark-store hubs and customer GPS coordinates across 10 million orders.
| Optimization Method | Execution Mechanism | Time (10M Rows) | Relative Speedup |
|---|---|---|---|
| df.iterrows() Loop | Pure Python row generator | 18 minutes 20s | 1x (Baseline) |
| df.apply(lambda) | Pandas Series iterator | 1 minute 15s | 14.6x speedup |
| Vectorized NumPy Math | C-level SIMD array operations | 0.24 seconds | 4,580x speedup |
| Numba @njit Kernel | LLVM JIT machine code | 0.12 seconds | 9,160x speedup |
Syntax & Core Code Implementation
import numpy as np
import cProfile
import pstats
from numba import njit
# Vectorized Haversine distance in pure NumPy
def haversine_vectorized(lat1, lon1, lat2, lon2):
R = 6371.0 # Earth radius in kilometers
dlat = np.radians(lat2 - lat1)
dlon = np.radians(lon2 - lon1)
a = (np.sin(dlat / 2.0) ** 2 +
np.cos(np.radians(lat1)) * np.cos(np.radians(lat2)) * np.sin(dlon / 2.0) ** 2)
c = 2 * np.arcsin(np.sqrt(a))
return R * c
# Numba Just-In-Time (JIT) compilation
@njit(fastmath=True)
def fast_moving_avg(arr, window):
n = len(arr)
out = np.empty(n - window + 1)
for i in range(len(out)):
out[i] = np.mean(arr[i : i + window])
return out
# Profiling script with cProfile
profiler = cProfile.Profile()
profiler.enable()
distances = haversine_vectorized(df['store_lat'].values, df['store_lon'].values, df['cust_lat'].values, df['cust_lon'].values)
profiler.disable()
stats = pstats.Stats(profiler).sort_stats('cumtime')
stats.print_stats(10)
Parameters & Arguments Breakdown
cProfile.Profile(): Built-in C-extension deterministic profiler measuring function invocation counts and elapsed runtimes.@njit: Compiles decorated Python function directly to native machine code via LLVM, bypassing the CPython interpreter.fastmath=True: Enables aggressive SIMD floating-point optimizations in Numba.
Step-by-Step Implementation
- Profile Before Optimizing: Run `python -m cProfile -s cumtime script.py` to identify the top 5 slowest functions.
- Vectorize Array Math: Extract underlying NumPy arrays (`df["col"].values`) and replace scalar math with array broadcasting.
- JIT-Compile Complex Logic: For nested algorithms that cannot be vectorized natively, decorate with `@njit`.
Common Mistakes & Limitations
- Iterating over DataFrames using `for i in range(len(df)): df.loc[i, ...]` ($O(N^2)$ indexing overhead), which is the slowest possible code in Python.
- Premature optimization: refactoring code before profiling, wasting time optimizing functions that account for < 2% of total execution runtime.
- Passing Pandas DataFrames or Series directly into `@njit` decorated functions; Numba requires raw NumPy arrays or primitive types.
Keyboard Shortcuts (Jupyter & VS Code)
| Action | Windows | Mac |
|---|---|---|
| Accurately benchmark single-line execution speed | %timeit in Jupyter | %timeit in Jupyter |
Pro Tips & Modern Best Practices
- Extract `.to_numpy()` or `.values` when passing Series into mathematical formulas to avoid Pandas index alignment overhead.
- In modern data stacks, consider Polars (`import polars as pl`) for multi-threaded Rust-speed DataFrame processing with identical memory footprints.