Back to Async, Concurrency & Performance

Profiling & Optimization

Find what's slow before you optimize. cProfile, py-spy, memray — the right tool for the right symptom. FIND_VIDEO: search 'python profiling cProfile py-spy memray' — recommended channel: mCoding / Anthony Shaw. Aim for 10 min or under.

17 minutesVideo LessonPDF notes
🎯 Free Guest Mode: You are learning for free. Sign in to save your completion progress and quiz answers.

Ready to continue?

Mark this lesson as complete when you're ready to proceed.

Key moments

  1. Optimization Decision Tree — Sebastiaan outlines the criteria for deciding when optimization is warranted versus premature.
  2. Baseline Naive Implementation — The duplicate movie search problem is introduced alongside its initial 3.5-second runtime benchmark.
  3. Profiling Decorator Setup — A custom cProfile wrapper decorator is constructed to inspect execution time per function call.
  4. Analyzing Profile Reports — The cumulative time metrics reveal that 24 million string lowercasing operations cause the bottleneck.
  5. Hoisting String Transformations — Transforming strings once during ingestion drops total execution time by more than ten-fold.
  6. Removing Redundant Functions — Inlining the haystack membership check eliminates function call overhead and halves runtime again.
  7. Algorithmic Redesign via Sorting — The quadratic search is replaced by in-place sorting and adjacent pairwise comparisons using zip.
PDF notes

Frequently asked questions

What is the difference between tottime and cumtime in cProfile?

Tottime measures time spent exclusively in the function body, while cumtime includes time spent in all downstream sub-functions.

Why is sorting faster than popping and scanning a list?

Repeatedly scanning an unsorted list creates $O(N^2)$ comparisons, whereas sorting takes $O(N \log N)$ and adjacent scans take $O(N)$.

When should code be redesigned instead of micro-optimized?

Redesign when data volumes grow significantly and profiling shows the asymptotic complexity ($O(N^2)$) remains the limiting constraint.

How was this lesson?

Your feedback helps us refine explanations and catch bugs.