Open in VS Code: From your cloned s26-06643 repository, run in the terminal:

code sse/optional/profiling/profiling.ipynb

View source on GitHub

Profiling and Optimization#

“Premature optimization is the root of all evil” — Donald Knuth. But when your code is too slow, you need to know where the bottleneck is before you can fix it. This lecture covers profiling tools to identify slow code and optimization techniques to speed it up.

Section 1: The Optimization Workflow#

Never optimize without profiling first. The workflow is:

  1. Write correct code — get it working first

  2. Measure — profile to find the actual bottleneck

  3. Optimize the bottleneck — only the slow part

  4. Measure again — verify the improvement

Your intuition about what is slow is often wrong. Profile first, optimize second.

Section 2: Timing with timeit#

For quick benchmarks, use timeit. It runs your code multiple times and reports the average.

import timeit
import numpy as np

# Compare list comprehension vs. numpy for squaring numbers
n = 10000
data = list(range(n))
arr = np.array(data)

list_time = timeit.timeit(lambda: [x**2 for x in data], number=1000)
numpy_time = timeit.timeit(lambda: arr**2, number=1000)

print(f"List comprehension: {list_time:.3f} s")
print(f"NumPy:              {numpy_time:.3f} s")
print(f"NumPy is {list_time / numpy_time:.1f}x faster")

In Jupyter notebooks, you can use the %%timeit magic:

%%timeit
result = [x**2 for x in range(10000)]

Section 3: cProfile — Function-Level Profiling#

cProfile is built into Python and shows you how much time is spent in each function.

import cProfile
import pstats
from io import StringIO

def slow_function():
    """A deliberately slow function for profiling."""
    total = 0
    for i in range(1000):
        total += sum(x**2 for x in range(1000))
    return total

def fast_helper():
    return sum(range(100))

def main_computation():
    result = slow_function()
    for _ in range(10):
        fast_helper()
    return result

# Profile the computation
profiler = cProfile.Profile()
profiler.enable()
result = main_computation()
profiler.disable()

# Print stats sorted by cumulative time
stream = StringIO()
stats = pstats.Stats(profiler, stream=stream).sort_stats("cumulative")
stats.print_stats(10)
print(stream.getvalue())

Reading cProfile Output#

Column

Meaning

ncalls

Number of times the function was called

tottime

Total time spent in the function (excluding sub-calls)

percall

tottime / ncalls

cumtime

Cumulative time (including sub-calls)

percall

cumtime / ncalls

Focus on functions with the highest cumtime — those are your bottlenecks.

From the Command Line#

python -m cProfile -s cumulative my_script.py

Section 4: line_profiler — Line-by-Line Profiling#

Once you know which function is slow, line_profiler shows you which lines are the bottleneck.

Install: pip install line_profiler

# In a script, decorate the function with @profile
@profile
def process_data(data):
    cleaned = [x for x in data if x > 0]          # Line 1
    normalized = [x / max(cleaned) for x in cleaned]  # Line 2
    result = sum(x**2 for x in normalized)         # Line 3
    return result

Run with:

kernprof -l -v my_script.py

This shows time spent on each line, making it easy to identify the exact bottleneck.

In Jupyter notebooks, use the %lprun magic:

%load_ext line_profiler
%lprun -f process_data process_data(my_data)

Section 5: Memory Profiling#

Sometimes the bottleneck is not CPU time but memory usage. memory_profiler shows memory consumption line by line.

Install: pip install memory_profiler

from memory_profiler import profile

@profile
def memory_hungry():
    a = [i for i in range(1_000_000)]      # ~8 MB
    b = [i**2 for i in range(1_000_000)]    # ~8 MB more
    del a                                    # Free ~8 MB
    c = sum(b)
    return c

Run with:

python -m memory_profiler my_script.py

In Jupyter:

%load_ext memory_profiler
%memit my_function()

Section 6: Optimization Techniques#

NumPy Vectorization#

Replace Python loops with NumPy operations wherever possible.

import numpy as np
import timeit

n = 100_000

# Slow: Python loop
def pairwise_distance_loop(points):
    n = len(points)
    distances = np.zeros((n, n))
    for i in range(n):
        for j in range(i + 1, n):
            d = np.sqrt(sum((points[i][k] - points[j][k])**2 for k in range(3)))
            distances[i, j] = d
            distances[j, i] = d
    return distances

# Fast: NumPy vectorized
def pairwise_distance_numpy(points):
    diff = points[:, np.newaxis, :] - points[np.newaxis, :, :]
    return np.sqrt(np.sum(diff**2, axis=-1))

# Benchmark with small arrays
points = np.random.rand(200, 3)

loop_time = timeit.timeit(lambda: pairwise_distance_loop(points.tolist()), number=1)
numpy_time = timeit.timeit(lambda: pairwise_distance_numpy(points), number=1)

print(f"Python loops: {loop_time:.3f} s")
print(f"NumPy:        {numpy_time:.5f} s")
print(f"Speedup:      {loop_time / numpy_time:.0f}x")

Numba JIT Compilation#

When NumPy vectorization is not possible (e.g., complex loop logic), Numba can JIT-compile Python to machine code:

from numba import njit
import numpy as np

@njit
def pairwise_distance_numba(points):
    n = points.shape[0]
    distances = np.zeros((n, n))
    for i in range(n):
        for j in range(i + 1, n):
            d = 0.0
            for k in range(3):
                d += (points[i, k] - points[j, k])**2
            d = np.sqrt(d)
            distances[i, j] = d
            distances[j, i] = d
    return distances

# First call compiles (slow), subsequent calls are fast
points = np.random.rand(1000, 3)
result = pairwise_distance_numba(points)  # Compilation + execution
result = pairwise_distance_numba(points)  # Just execution (fast)

Numba works best with:

  • NumPy arrays (not lists, dicts, or custom classes)

  • Numerical code (not string processing or I/O)

  • Loops that cannot be easily vectorized

Other Optimization Strategies#

Strategy

When to Use

Caching/memoization

Repeated calls with same arguments (functools.lru_cache)

Generators

Processing large datasets that don’t fit in memory

Parallel processing

CPU-bound tasks that can be split (multiprocessing, joblib)

Better algorithms

O(n²) → O(n log n) is almost always worth it

Sparse matrices

Matrices that are mostly zeros (scipy.sparse)

Exercise: Profile and Optimize a Slow Function#

The function below simulates a Monte Carlo estimation of pi. It works, but it is slow.

import random
import time

def estimate_pi_slow(n_samples):
    """Estimate pi using Monte Carlo method (deliberately slow)."""
    inside = 0
    points_x = []
    points_y = []

    for _ in range(n_samples):
        x = random.random()
        y = random.random()
        points_x.append(x)
        points_y.append(y)

        distance = (x**2 + y**2)**0.5
        if distance <= 1.0:
            inside += 1

    pi_estimate = 4 * inside / n_samples
    return pi_estimate

start = time.time()
pi = estimate_pi_slow(1_000_000)
elapsed = time.time() - start
print(f"Pi ≈ {pi:.6f} (took {elapsed:.2f} s)")

Tasks:

  1. Profile estimate_pi_slow using cProfile to identify the bottleneck

  2. Create an optimized version using NumPy vectorization

  3. Create another optimized version using Numba @njit

  4. Benchmark all three versions with timeit

  5. Report the speedup factor for each optimization

Bonus: Can you get the function to run in under 10 ms for 10 million samples?

Summary#

Tool

What It Measures

When to Use

timeit

Execution time of small code snippets

Quick benchmarks

cProfile

Time per function

Finding which function is slow

line_profiler

Time per line

Finding which line is slow

memory_profiler

Memory per line

Finding memory bottlenecks

Optimization order of preference:

  1. Better algorithm (biggest gains)

  2. NumPy vectorization (easy, large speedup)

  3. Numba JIT (when vectorization is hard)

  4. Caching (for repeated computations)

  5. Parallelism (for independent tasks)

Always measure before and after. If you cannot measure the improvement, the optimization was not worth it.

Tips and Tricks#

  • Profile before optimizing: Never guess where the bottleneck is — cProfile takes seconds to run and tells you exactly where time is spent.

  • Prompt: “Profile this function and suggest optimizations”: Give AI the profiling output and it will identify the bottleneck and suggest fixes.

  • Use %%timeit in notebooks for quick benchmarks: It handles warmup and repetition automatically — more reliable than time.time().

  • Prompt: “Rewrite this loop using NumPy vectorization”: This is one of AI’s strongest optimization patterns — it almost always produces correct, faster code.

  • Optimize the innermost loop first: A 2x speedup on code that runs 1 million times matters more than a 10x speedup on code that runs once.

  • Prompt: “Add @njit to this function and adjust it for Numba compatibility”: Numba has restrictions (no dicts, limited string ops) — AI knows what to change.

  • Measure memory too: memory_profiler catches memory leaks that do not show up in timing benchmarks.

  • Cache expensive computations: functools.lru_cache for pure functions, joblib.Memory for disk-based caching — ask AI to add the appropriate one.

Foundational Concepts to Commit to Memory#

  • Profile before optimizing — your intuition about what is slow is often wrong. Measure first, then fix the actual bottleneck.

  • cProfile identifies which function is slow; line_profiler identifies which line within that function is slow. Use them in sequence.

  • timeit is for quick benchmarks of small snippets — it runs your code many times and reports the average, which is more reliable than a single time.time() call.

  • NumPy vectorization replaces Python loops with C-level array operations — this is the single most impactful optimization for numerical code.

  • Numba @njit JIT-compiles Python loops to machine code — use it when the loop logic is too complex to vectorize with NumPy.

  • Algorithm improvements (e.g., O(n^2) to O(n log n)) almost always beat micro-optimizations. Check your algorithm complexity first.

  • memory_profiler shows memory usage line by line — critical when your code runs out of RAM or triggers excessive swapping.

  • functools.lru_cache memoizes function results — if you call the same function with the same arguments repeatedly, cache the result instead of recomputing.

Knowing vs. Doing: Reflection#

Profiling is a skill that separates people who make code fast from people who think they are making code fast. Without profiling, optimization is guessing. You might spend an hour rewriting a function that accounts for 2% of your runtime while ignoring the one that accounts for 85%. The tools in this lecture — timeit, cProfile, line_profiler — give you the data to make informed decisions. And you need to know they exist, because AI agents cannot profile your code for you. They can suggest optimizations, but only you can measure whether those optimizations actually helped on your specific data and hardware.

That said, AI agents are extraordinarily good at the optimization step once you have identified the bottleneck. Tell an AI “this function is slow because of a nested Python loop over a 10,000-element array” and it will give you a vectorized NumPy version, a Numba version, and maybe a scipy shortcut you did not know about. The AI expands your optimization toolkit far beyond what you personally know. You might not have heard of Numba before today — but now you know it exists, and an AI can help you apply it to your specific problem in minutes.

The honest truth about performance optimization is that most scientific code does not need it. If your script runs in 10 seconds and you run it once a day, spending two hours optimizing it is a net loss. But when your Monte Carlo simulation takes 6 hours, or your data pipeline cannot keep up with incoming data, profiling and optimization become essential. Know the tools, know when to reach for them, and let AI help you apply them. The combination of your profiling data and an AI’s optimization knowledge is more powerful than either alone.

Additional Resources#