Performance & compiler optimization
12 min lesson
- Performance optimization is the practice of making a program run faster or use fewer resources, and compiler optimization is the set of transformations the compiler applies to speed up your code automatically.
- This matters because slow programs frustrate users and waste resources, but careless optimization can introduce bugs.
- Think of the compiler as a chef who rearranges your recipe to cook faster without changing the final dish; you should still measure the result.
- Compiler optimization levels like -O0, -O1, -O2 and -O3 trade compile time and code size for runtime speed.
- Common optimizations include inlining small functions, removing dead code, keeping values in registers, and reordering instructions.
- Measurement tools like profiling (gprof, perf) show where time is really spent, so you optimize the hot spots, not guesses.
- The computer's CPU executes the optimized instructions; the compiler must preserve the program's observable behavior as long as the code has no undefined behavior.
- The syntax is: gcc -O2 -Wall -Wextra main.c -o app to build with optimization and warnings.
- A realistic use: speeding up a hot loop by using a better algorithm first, then letting -O2 inline small helpers.
- A surprising detail: undefined behavior gives the compiler freedom to do unexpected things at -O2, so correct code matters more, not less, when optimizing.
- The example program shows a simple loop whose work the compiler can optimize, with comments explaining what -O2 might do.
- Optimize the algorithm first; the compiler cannot fix a bad approach.
- Measure before and after; do not guess where the time goes.
- Use -O2 for release builds and keep warnings on.
- Avoid undefined behavior, especially in optimized builds.
- Performance work is careful work. You are thinking like an engineer!
#include <stdio.h>
// A small function the compiler may inline at -O2
static int square(int x) {
return x * x;
}
int main(void) {
// Sum the squares of 1..10
int total = 0;
for (int i = 1; i <= 10; i++) {
// -O2 may inline square and keep total in a register
total += square(i);
}
// Print the sum: 1 + 4 + 9 + ... + 100 = 385
printf("Total: %d\n", total);
return 0;
}
// Build with: gcc -O2 -Wall -Wextra main.c -o app
// Try -O0 to compare; the output is the same, but -O2 may run faster.What happens: Total: 385
Breaking it down
Small helper
static int square(int x) { return x * x; }A tiny function the compiler can inline at -O2, removing call overhead and possibly folding constants.
Hot loop
for (int i = 1; i <= 10; i++) total += square(i);The compiler may unroll the loop or compute the sum at compile time, since all inputs are known.
Optimization flags
-O2Enables a standard set of safe optimizations. -O3 adds more aggressive ones at the cost of code size.
Warnings
-Wall -WextraKeep warnings on during optimization; they catch bugs that optimization can magnify.
Optimization levels
| Flag | Speed | Code size | Use |
|---|---|---|---|
| -O0 | Slowest | Small | Debugging |
| -O1 | Moderate | Small | Balanced |
| -O2 | Fast | Medium | Release default |
| -O3 | Fastest | Larger | Hot loops, numeric code |
| -Os | Moderate | Smallest | Embedded, size-limited |
A helpful analogy
Compiler optimization is like a chef rearranging your recipe to cook faster without changing the final dish. You can also buy better ingredients (a better algorithm) or measure how long each step takes (profiling) to find the real bottleneck.
Nesting rules
- 1.Optimize the algorithm before the micro-details; a better algorithm wins big.
- 2.Measure with profiling tools before and after changes; do not guess.
- 3.Keep -Wall -Wextra on at every optimization level to catch bugs.
- 4.Avoid undefined behavior; at -O2 the compiler may assume it never happens.
Common mistakes
Optimizing without measuring
Avoid
rewrite code because it looks slowUse instead
profile first, then optimize the hot spotsMost of the time is spent in a small part of the code. Optimizing elsewhere wastes effort and adds risk.
Debugging with -O2
Avoid
gdb ./app built with -O2Use instead
build with -O0 -g for debuggingOptimization reorders code and removes variables, making stepping and inspection confusing. Debug at -O0.
Relying on undefined behavior in optimized builds
Avoid
int x = INT_MAX + 1; // UBUse instead
check before addingAt -O2 the compiler may exploit UB and produce surprising results. UB is more dangerous, not less, with optimization.
Quick tips
- •Use perf or gprof to find the top functions by time.
- •Try -O2 vs -O0 on a bigger loop to see the speed difference.
- •Prefer clear code first; optimize only when measurements justify it.
- •Build with -g and -O2 together to keep debug symbols for profiling.
- •Read the compiler's vectorization reports (-fopt-info-vec) to see what it optimized.