Search code examples
cprofilinggprof

What does the -p and -g flag in compiler?


I have been profiling a C code and to do so I compiled with -p and -g flags. So I was wandering what do these flags actually do and what overhead do they add to the binary?


Solution

  • -p provides information for prof, and -pg provides information for gprof.

    Let's look at the latter. Here's an explanation of how gprof works, but let me condense it here.

    When a routine B is compiled with -pg, some code is inserted at the routine's entry point that looks up which routine is calling it, say A. Then it increments a counter saying that A called B.

    Then when the code is executed, two things are happening. The first is that those counters are being incremented. The second is that timer interrupts are occurring, and there is a counter for each routine, saying how many of those interrupts happened when the PC was in the routine.

    The timer interrupts happen at a certain rate, like 100 times per second. Then if, for example, 676 interrupts occurred in a routine, you can tell that its "self time" was about 6.76 seconds, spread over all the calls to it.

    What the call counts allow you to do is add them up to tell how many times a routine was called, so you can divide that into its total self time to estimate how much self time per call. Then from that you can start to estimate "cumulative time". That's the time spent in a routine, plus time spent in the routines that it calls, and so on down to the bottom of the call tree.

    This is all interesting technology, from 1982, but if your goal is to find ways to speed up your program, it has a lot of issues.