Skip to the page

Performance and memory · mid

Profiling a slow program and a slow start

Measure before you change code. Compare wall time with CPU time, use a profiler to find the biggest cost, and fix the algorithm before micro-tuning. Slow start-up usually comes from imports or work done at import time.

The notes

What you must know

  • Reproduce with realistic data. Compare wall time with CPU time: low CPU means the program waits on a database, network or disk, not on slow Python.
  • cProfile is a tracing profiler with overhead: python -m cProfile -o out.prof, sort by cumulative and own time, view with snakeviz.
  • Sampling profilers such as py-spy attach to a running process without a restart: top, dump, and record for a flame graph.
  • Line level: line_profiler. Memory: memray or Scalene. Small comparisons: timeit.
  • Fix the biggest cost first, and check the algorithm before micro-tuning. A function that takes 2% of the time is not worth the effort.
  • If runtime grows faster than the data (30 times the data and 100 times the time) the code is worse than linear, often quadratic: a list used for membership, or a nested loop.
  • A deepcopy of a big structure on every request costs time in proportion to its size. The cause is often defensive copying that hides a mutation bug. Share immutable data instead; do not round-trip through JSON, which loses types such as Decimal and datetime.
  • Slow start: python -X importtime shows time per import. Move heavy imports into the functions that use them, avoid work at import time (network calls, big files, building clients), and run python -m compileall at build time for read-only images.

The red pen

Common traps: mistake → fix

  • Mistake: Guess and rewrite

    Fix: profile first.

  • Mistake: Buy a bigger machine or add servers

    Fix: that does not fix a quadratic loop or a blocking call.

  • Mistake: Wrap a quadratic loop in multiprocessing

    Fix: fix the algorithm first.

  • Mistake: Caching the deepcopy result is a fix

    Fix: it goes back to sharing mutable data.

Easy to hard

Questions interviewers ask, easy to hard

  1. A Python job is slow. How do you find where the time goes?
  2. What is the difference between cProfile and py-spy?
  3. Why does 30 times more data take about 100 times longer?
  4. p95 went from 120 ms to 900 ms and 60% of the time is in deepcopy. What do you do?
  5. A command-line tool takes 6 seconds to print --help. How do you find out why?

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview