Sub topic 3
Finding Memory Hogs and Choosing Faster Tools
Assume you can write Python functions, use lists and sets, run scripts from a terminal, and install packages with pip. First measure the resource that is slow: memory, CPU time, or waiting time.
Finding memory hogs with `tracemalloc`
tracemalloc records where Python allocates memory. Take snapshots before and after a suspected operation, then compare them.
import tracemalloc
tracemalloc.start()
data = [str(i) for i in range(100_000)]
snapshot = tracemalloc.take_snapshot()
for stat in snapshot.statistics("lineno")[:3]:
print(stat)The output names source lines, allocated size, and allocation count. It tracks Python allocations, not every allocation made by native libraries.
Zooming in with line-level profiling
After cProfile identifies a slow function, a line profiler can show which line inside it consumes time. Install a tool such as line_profiler, decorate the target function, and run its command-line interface. This adds overhead, so profile a representative workload rather than production traffic.
Profiling running programs with a sampling profiler
A sampling profiler periodically inspects the call stack instead of tracing every function call. Tools such as py-spy can attach to a running process with low overhead:
py-spy top --pid 12345Sampling is useful when the program is long-running or difficult to reproduce. It can show native stack frames, but it may miss very short operations.
Moving loops into NumPy
For large numeric arrays, NumPy performs loops in compiled code:
import numpy as np
values = np.arange(1_000_000, dtype=np.int64)
total = int((values * values).sum())
print(total)This vectorization often beats a Python loop. It requires compatible numeric data and may use more temporary memory.
Threads, processes, and the GIL
The global interpreter lock (GIL) limits simultaneous execution of Python bytecode in typical threads. Use threads for I/O-bound work, such as network requests. Use processes for CPU-bound Python work when the tasks are large enough to justify process and data-transfer costs. Native numeric code may release the GIL.
Keeping the speedup
Add a repeatable benchmark to continuous integration. Measure a realistic input, define an acceptable limit, and fail when performance regresses. Avoid tests that depend on an exact wall-clock time on shared machines.
When to go native
Try a better algorithm, data structure, or vectorized operation first. Use Cython or Numba when a stable hot loop remains. Write a C extension only when you need maximum control and can maintain a more complex build and debugging process.
Exercise
Which tool should you try first for a slow Python loop over a large numeric array?
Show answer
Measure it, then try NumPy vectorization before choosing processes or native code.