6

I wonder if there's any API within gprof to enable and disable profiling at runtime by the monitored application. I'm interested on disabling the profiling of certain parts of the code and enabling it to focus on those that are interesting to me. I mean, is there a way to avoid do this?

int main (void)
{

  // disable gprof ?
  uninteresting_routine();
  // enable gprof ?

  interesting_routine();
}

This link from the GCC website referring the instrumentation options does not seem to include any reference to this functionality.

Harald
  • 3,110
  • 1
  • 24
  • 35

2 Answers2

4

There's an undocumented and hidden way of doing this that works on some systems (at least some, if not all, versions of glibc and some BSDs).

$ cat foo.c
extern void moncontrol(int);

static void
foo(void)
{
}

static void
bar(void)
{
}

int
main(int argc, char **argv)
{
    moncontrol(0);
    foo();
    moncontrol(1);
    bar();
    return 0;
}
$ cc -o foo -pg foo.c && ./foo
$ gprof foo | egrep 'foo|bar'
  0.00      0.00     0.00        1     0.00     0.00  bar
[1]      0.0    0.00    0.00       1         bar [1]
   [1] bar

Glibc doesn't have a prototype or man-page for this function, but it does exist.

Art
  • 19,807
  • 1
  • 34
  • 60
  • Awesome thank you! It also works with the Intel compiler. Simply curiosity, do you remember where did you get this information? – Harald Sep 30 '16 at 12:49
  • @Harald I worked on profiling code in a kernel once and looked at how our libc did things. When I needed this on linux some 10 years ago I remembered it, checked and linux implemented the same thing. – Art Sep 30 '16 at 13:06
  • @Harald btw. This shouldn't depend on the compiler at all since the compiler just uses hooks that libc provides. – Art Sep 30 '16 at 13:08
  • Just tested this with MSYS64. Works too. Shame it's only documented in the BSD manual as far as I can see ; it makes me uneasy to implement it in production. – adentinger Feb 25 '20 at 14:05
2

The accepted answer is correct. Just wanted to remind C++ programmers to use

extern "C" void moncontrol(int);