Course contentsShow
← C
Lesson 1182 of 1,21916. Practice and ProjectsFree lesson

Introduction to the `gprof` profiler

Introduction to the gprof profiler

What you'll learn: How to use the gprof tool to identify which functions in your C program are consuming the most execution time.

Finding the bottlenecks

Imagine you are a chef running a busy kitchen. If customers are complaining about long wait times, you need to know exactly where the delay is happening. Is the oven too slow? Is the sous-chef chopping onions at a snail's pace? Or is the dishwasher overwhelmed? Without data, you are just guessing.

In programming, a profiler is your kitchen stopwatch. gprof is a classic tool for Linux and Unix systems that tracks how many times each function is called and how many milliseconds the CPU spends inside them. This allows you to stop guessing and start optimizing the parts of your code that actually matter.

The Three-Step Process

To use gprof, you don't just run your program normally. You must follow a specific workflow:

  1. Compile with profiling enabled: You must tell the compiler (gcc) to insert special "instrumentation" code by adding the -pg flag.
  2. Run the program: Execute your program as usual. When it finishes, it will automatically generate a file named gmon.out.
  3. Analyze the report: Use the gprof command to read that file and turn it into a human-readable "Flat Profile."

A Concrete Example

Suppose we have a program that calculates squares and cubes in a loop.

#include <stdio.h>

void calculate_squares(int n) {
    for (int i = 0; i < n; i++) {
        int temp = i * i;
    }
}

void calculate_cubes(int n) {
    for (int i = 0; i < n; i++) {
        int temp = i * i * i;
    }
}

int main() {
    printf("Starting calculations...\n");
    for (int i = 0; i < 1000; i++) {
        calculate_squares(100000);
        calculate_cubes(100000);
    }
    return 0;
}

To profile this, you would run:

  1. gcc -pg main.c -o my_app
  2. ./my_app
  3. gprof my_app gmon.out > analysis.txt

Inside analysis.txt, you will see a table. If calculate_cubes takes up 70% of the total time, gprof will tell you exactly that. You now know that even if you make calculate_squares twice as fast, it will barely impact the overall speed because the "bottleneck" is in the cubes function.

Key takeaway

The gprof profiler helps you find "hotspots" in your code by recording function execution times, provided you compile with the -pg flag.