gprof profiler

gprof is a profiler that helps you see how much time is spent in each section of your program. Bottlenecks can be identified and that code made more efficient. In the examples below we assume you are using a command-line environment, such as Replit.

Running gprof

For code that compiles and runs, follow these steps by typing them in on the command line:

  1. From the command line compile with the option for profiling (-pg). If your program is called main.c, then from the command line compile it using:
    gcc -pg main.c
    This will create the default executable called
    a.out, and will set up the system so when you next run the program it will keep track of time spent.

  2. Now that profiling has been turned on, run the program, which will create a file called gmon.out that keeps track of time spent in each part of your program:
    ./a.out
    Run it just as you would normally, exiting normally without killing the process. (You may need to edit the program to avoid exiting by killing it with Cntrl-C
    .)

  3. Analyze the results stored in gmon.out using gprof, redirecting the output to a file called output.txt
    gprof ./a.out > output.txt
    Then examine the contents of
    output.txt using your favorite text editor. Alternatively when you run gprof you can pipe your gprof output into the more UNIX utility to just look at it on-screen:
    gprof ./a.out | more

Example

Assume you have the following program (available as Example gprofDemo in Replit), which has three nested loops:

Following the above gprof steps gives us output shown below (slightly edited for formatting). The top chart shows the percent of time and number of calls for each function. The bottom chart shows for each function (with an [index] number) the functions that call it (listed above), and the functions it calls (listed below).