Profiling with gprof & perf in C
Profilers replace performance hunches with measurements: gprof (compile -pg, run, gprof ./app) attributes run time per function with call counts, while Linux perf samples hardware counters (perf record/report, perf stat) with near-zero overhead — cycles, cache misses, branch misses. Measure first invariably reveals the hotspot isn't where intuition placed it.
Profile optimized builds (-O2, matching release) since -O0 profiles mislead; separate CPU-bound from I/O-bound before optimizing (faster code can't fix waiting on disk); and re-measure after every change — optimizations that don't move the number get reverted.
gprof for call graphs
gcc -pg, run the workload, gprof ./app gmon.out — per-function time plus who-called-whom, zero setup beyond the flag.
perf for hardware truth
perf stat ./app reports cycles, instructions, cache-misses; perf record/report hotspots by symbol with call graphs (-g).
Profile release builds
-O2 binaries behave nothing like -O0 ones — inlining and vectorization move hotspots, so measure what ships.
Revert what doesn't move
Every optimization ends with a before/after number — no improvement measured means the change gets backed out.
$ gcc -pg -O2 app.c -o app$ ./app < big-input.txt$ gprof ./app gmon.out | head -8$ perf stat ./app < big-input.txtRecommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in C yourself — building beats watching.