How exactly does gperftools CPU profiler start?

gperftools documentation says that libprofiler should be linked into a target program:

$ gcc myprogram.c -lprofiler

(without changing a code of the program).

And then program should be run with a specific environment variable:

CPUPROFILE=/tmp/profiler_output ./a.out

The question is: how does libprofile have a chance to start and finish a profiler when it is merely loaded, but its functions are not called?

There is no constructor function in that library (proof). All occasions of "CPUPROFILE" in library code do not refer to any place where profiler is started.

I am out of ideas, where to look next?


As per the documentation the linked webpage, under Linking the library, it describes that the -lprofiler step is the same as linking against the shared object file with LD_PRELOAD option.

The shared object file isn't the same as just the header file. The header file contains function declarations which are looked up by when compiling a program , so the names of the functions resolve, but the names are just names, not implementations. The shared object file (.so) contains the implementations of the functions. For more information see the following StackOverflow answer.

Source file of /trunk/src/profiler.cc on Line 182, has a CPUProfiler constructor, that checks for whether profiling should be enabled or not based on the CPUPROFILE environment variable (Line 187 and Line 230).

It then calls the Start function on Line 237. As per the comments in this file, the destructor calls the Stop function on Line 273.

To answer your question I believe Line 132 CpuProfiler CpuProfiler::instance_; is the line where the CpuProfiler is instantiated.

This lack of clarity in the gperftools documentation is known issue see here.


I think the profiler gets initialized with the REGISTER_MODULE_INITIALIZER macro seen at the bottom of profile-handler.cc (as well as in heap-checker.cc, heap-profiler.cc, etc). This calls src/base/googleinit.h which defines a dummy static object whose constructor is called when the library is loaded. That dummy constructor then calls ProfileHandlerRegisterThread() which then uses the pthread_once variable to initialize the singleton object (ProfileHandler::instance_).

The function REGISTER_MODULE_INITIALIZER simulates the module_init()/module_exit() functions seen in Linux loadable kernel modules.

(my answer is based on the 2.0 version of gperftools)

链接地址: http://www.djcxy.com/p/87948.html

上一篇: GPerfTools / pprof:虚线是什么意思?

下一篇: gperftools CPU分析器到底如何启动?