Learn C
#include "advanced/profiling.h"

Profiling with gprof & perf in C

#concept

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.

#how it works
1

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.

2

perf for hardware truth

perf stat ./app reports cycles, instructions, cache-misses; perf record/report hotspots by symbol with call graphs (-g).

3

Profile release builds

-O2 binaries behave nothing like -O0 ones — inlining and vectorization move hotspots, so measure what ships.

4

Revert what doesn't move

Every optimization ends with a before/after number — no improvement measured means the change gets backed out.

#example
$ gcc -pg -O2 app.c -o app
$ ./app < big-input.txt
$ gprof ./app gmon.out | head -8
$ perf stat ./app < big-input.txt
Output
%time seconds name
62.1 1.40 parse_record
21.3 0.48 hash_insert
...
1,402,111,903 cycles, 0.41 IPC
1The -pg build plus a realistic workload produces profiling data reflecting actual use.
2gprof attributes 62% to parse_record — the optimization target, not the suspected hash_insert at 21%.
3perf's low IPC (0.41 instructions per cycle) hints memory stalls — measurement directing the next experiment.
#use cases
Finding real hotspots before optimizing anything
Call-graph analysis of who costs what via gprof
Hardware-counter diagnosis (cache misses, IPC) via perf
Before/after numbers gating every performance change

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in C yourself — building beats watching.