Profiling and performance
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 -20timeittimes a small snippet, repeated to reduce noise.cProfileshows which functions take the most total time (-s cumtimesorts by it).- For memory, use
tracemallocfrom 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
setordict. - 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.