appzasGamesToolsDevLearnCheat sheetsQuick calcsConvertersReferenceNetworkTimeCalculatorsCompareLLM prices

Profiling and performance

Lesson 5 of 511 minAdvanced

Measure first, then optimise the part that actually costs time.

Most of a program's time is spent in a small part of it, and it is rarely where you expect. Measure before you change anything.

import timeit
print(timeit.timeit("sum(range(1000))", number=10_000))
python3 -m cProfile -s cumtime script.py | head -20
  • timeit times a small snippet, repeated to reduce noise.
  • cProfile shows which functions take the most total time (-s cumtime sorts by it).
  • For memory, use tracemalloc from the standard library.

Common wins

  • Use the right data structure: membership tests are O(n) on a list but O(1) on average on a set or dict.
  • Build strings with "".join(parts) instead of += in a loop.
  • Move work out of loops, and cache repeated results with functools.cache.
  • Use built-ins (sum, sorted, min) and comprehensions, which run in C.
  • For numeric arrays, use NumPy instead of Python loops.
ids = set(big_list)           # build once
for x in items:
    if x in ids:              # fast lookup
        ...

CarefulDo not optimise for speed what you have not measured. Clear code that is slightly slower is usually better than clever code nobody can maintain.

Test yourself

Answer all the questions, then check them. Finish with every answer right to mark the lesson as done.

1. What should you do before optimising?
2. Why is x in my_set faster than x in my_list for large collections?
Hintpython3 -m cProfile -s cumtime ...

Key terms