Python theorytheory 0/50 · 0%
Tooling · hard

44. Performance: profiling and complexity awareness

Measuring instead of guessing; common complexity traps.

Before optimizing, measure. `time.perf_counter()` gives simple timing; the `timeit` module benchmarks small snippets more rigorously by running them many times.

python
import timeit

timeit.timeit("sum(range(1000))", number=10000)

# common trap: repeated string concatenation in a loop is O(n^2)
result = ""
for chunk in chunks:
    result += chunk   # slow for many chunks

# better: O(n)
result = "".join(chunks)

Checking membership with `in` is O(1) average on a `set`/`dict` but O(n) on a `list`; for repeated lookups, converting a list to a set upfront can turn an O(n²) algorithm into O(n).

Check your understanding

  1. 1. Why is repeated `result += chunk` in a loop often slow?

  2. 2. What's the time complexity of `x in some_list` vs `x in some_set`?

  3. 3. What is `timeit` used for?