Python for Data Analytics & AutomationLesson 40 of 41
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 MethodExecution MechanismTime (10M Rows)Relative Speedup
df.iterrows() LoopPure Python row generator18 minutes 20s1x (Baseline)
df.apply(lambda)Pandas Series iterator1 minute 15s14.6x speedup
Vectorized NumPy MathC-level SIMD array operations0.24 seconds4,580x speedup
Numba @njit KernelLLVM JIT machine code0.12 seconds9,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

  1. Profile Before Optimizing: Run `python -m cProfile -s cumtime script.py` to identify the top 5 slowest functions.
  2. Vectorize Array Math: Extract underlying NumPy arrays (`df["col"].values`) and replace scalar math with array broadcasting.
  3. 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)

ActionWindowsMac
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.
Performance Optimization: Vectorization, | DataCliq