Profiling C Code on Ubuntu: Complete gprof Performance Guide

Overview

Pinpointing computation bottlenecks is a fundamental step in optimizing native applications. In this walk-through, we explore using the GNU profiler (gprof) under Ubuntu to isolate CPU-intensive routines in C codebases. From configuring instrumentation compiler flags and capturing runtime metrics to deciphering flat profiles and call trees, this guide walks you through actionable performance profiling workflows.

1. Setting Up Prerequisites and Crafting a Benchmark C Program

Begin by pulling the standard development toolchain and binary manipulation packages onto your Ubuntu workstation via apt-get update -qq && apt-get install -y build-essential binutils.

apt-get update -qq && apt-get install -y build-essential binutils

Create an isolated workspace for compiling and analyzing the test binaries by executing mkdir -p ~/gprof_demo && cd ~/gprof_demo.

mkdir -p ~/gprof_demo && cd ~/gprof_demo

To demonstrate distinct timing metrics and execution frequencies, populate profile_test.c with two computational routines (slow_function and fast_function) possessing substantially different loop counts.

![cat « ‘EOF’ > profile_test.c #include <stdio.h>

void slow_function() { volatile unsigned long long count = 0; for (unsigned long long i = 0; i < 50000000ULL; i++) { count += i; } }

void fast_function() { volatile unsigned long long count = 0; for (unsigned long long i = 0; i < 10000000ULL; i++) { count += i; } }

int main() { printf("[INFO] Starting performance profiling demo…\n"); for (int i = 0; i < 5; i++) { slow_function(); } for (int i = 0; i < 10; i++) { fast_function(); } printf("[INFO] Finished execution successfully.\n"); return 0; } EOF](captures/s01_c03_cat_____EOF____profile_test_c__include__stdio_h.png)

Verify that the C source code was written correctly by running cat profile_test.c.

cat profile_test.c

2. Compiling with -pg Instrumentation and Capturing Runtime Data

Switch into your dedicated test directory using cd ~/gprof_demo.

cd ~/gprof_demo

Compile the C code using gcc -pg -O2 profile_test.c -o profile_test. Supplying the -pg flag instructs GCC to inject sample-gathering hooks into function prologues, recording call edges and execution ticks alongside optimized machine code.

gcc -pg -O2 profile_test.c -o profile_test

Ensure that the target executable binary is compiled and holds appropriate permissions by running ls -l profile_test.

ls -l profile_test

Run the instrumented binary directly using ./profile_test. As the process terminates normally, the runtime profiling hook dumps execution frequency and timing samples into a newly generated gmon.out file in the current working directory.

./profile_test

Inspect the generated sampling artifact and its storage footprint by executing ls -lh gmon.out. This raw binary data will serve as the input for our analysis pass.

ls -lh gmon.out

3. Extracting the Flat Profile via gprof

Navigate back to the project workspace using cd ~/gprof_demo.

cd ~/gprof_demo

Correlate the executable binary symbols with the collected runtime telemetry by running gprof profile_test gmon.out > analysis_report.txt. The utility translates address offsets into human-readable function signatures and outputs a structured breakdown into analysis_report.txt.

gprof profile_test gmon.out > analysis_report.txt

Inspect the initial summary section using head -n 25 analysis_report.txt. The flat profile highlights the exact CPU time percentage (% time), cumulative duration, and invocation tallies (calls) associated with each routine.

head -n 25 analysis_report.txt

4. Inspecting Call Graphs and Filtering Profile Metrics

Return to your workspace by running cd ~/gprof_demo.

cd ~/gprof_demo

To isolate structural relationships across functions, query the Call Graph section using grep -A 15 -B 2 "Call graph" analysis_report.txt. This snippet illustrates which parent routines trigger specific callee functions along with their propagation metrics.

grep -A 15 -B 2 “Call graph” analysis_report.txt

To strip verbose commentary and field explanations while retaining purely the flat profile metrics, execute gprof -p -b profile_test gmon.out. The -p switch targets the flat profile, while -b activates brief mode to eliminate boilerplate legends.

gprof -p -b profile_test gmon.out

Similarly, run gprof -q -b profile_test gmon.out to isolate call-tree relationships. The -q option isolates the call graph while -b suppresses documentation text, delivering a clean view of parent-child invocation chains and associated execution overheads.

gprof -q -b profile_test gmon.out

You now have a complete workflow for instrumenting, tracking, and diagnosing runtime performance of C applications on Ubuntu with GNU gprof. Leveraging these profiles allows you to focus refactoring efforts directly on true hotspots for maximum computational efficiency.