Performance Optimization & Profiling
Prerequisites: Testing in C
Measure before optimizing — gprof or perf (Linux) show where a
program actually spends its time, rather than guessing.
High-value, C-specific things worth knowing once a real bottleneck is found:
- Compiler optimization flags (
-O2, sometimes-O3) let the compiler restructure code for speed — always measure the optimized build, since debug builds (-O0) can be dramatically slower. - Cache-friendly memory access — looping over a 2D array row-by-row (matching how it's actually laid out in memory) is often noticeably faster than column-by-column.
- Avoiding unnecessary
malloc/freecalls in a hot loop — allocation has real overhead; reuse a buffer instead of reallocating it every iteration where possible.
Common mistakes
- Benchmarking a debug build (
-O0, with sanitizers enabled) and drawing conclusions about real-world performance from it.