advanced Estimated learning time: 4 h

2.17 Profiling and making Python fast

You can find the slow line instead of guessing.

Before:00. Orientation & SetupUnlocks:03. Data Handling & Analysis04. Classical AI — Agents, Search & Knowledge Representation

Profiling finds the actual slow line, which is reliably not the one suspected, and this topic makes evidence-first optimisation the habit: cProfile and line profilers to locate, vectorisation and caching to cure, Numba and Cython for the rare remainder. It closes the Python module because optimisation needs everything before it. The rule it enforces is measure first — rewriting for speed without a profile is how readable code becomes unreadable while staying slow.

Work through these

  • cProfile, line_profiler, memory_profiler

    Three profilers, giving whole-program, per-line and memory views. Measuring before optimising is the rule this item exists to establish.

  • Vectorizing loops with NumPy

    Replacing element-by-element loops with array operations is usually the largest single speed improvement available in numerical Python. It is also what the rest of this subject assumes you can do.

  • Numba, Cython and when they pay off

    Two ways of compiling Python-like code to machine speed, each suiting different situations. They are worth reaching for after vectorisation, not before.

  • Caching and algorithmic wins first

    Caching a repeated computation and choosing a better algorithm both beat micro-optimisation. The order of attack is algorithm, then vectorisation, then compilation.

Sign in to keep your progress.

Free resources

Links last checked 29 Aug 2026.

Stuck here?

Ask a mentor. A real person answers, and they can see exactly which topic you're on. Usually within a couple of working days.

Checking your session…

Topics shown in module order.