HOWTO: using gprof
with multithreaded applications
What is gprof
?
gprof
is the GNU Profiler, a tool used when tracking which
functions are eating CPU in your program. Anyway, you should already be
familiar with it if you got interested in this page.
One problem with gprof
under certain kernels (such as Linux)
is that it doesn’t behave correctly with multithreaded applications. It
actually only profiles the main thread, which is quite useless.
Workaround
There is an easy, but surprisingly not very widespread fix for this
annoying gprof
behaviour. Basically, gprof
uses the
internal ITIMER_PROF
timer which makes the kernel deliver
a signal to the application whenever it expires. So we just need to pass this
timer data to all spawned threads.
Example
It wouldn’t be too hard to put a call to setitimer
in each
function spawned by a thread, but I thought it would be more elegant to
implement a wrapper for pthread_create
.
Daniel Jönsson enhanced my code so that it could be used in a preload library without having to modify the program. It can also be very useful for libraries that spawn threads without warning, such as libSDL. The result code is shown below and can be downloaded ():
/* gprof-helper.c -- preload library to profile pthread-enabled programs
|
History of this document
- 13 Dec 2004: use __attribute__((constructor)) instead of _init, and converted to UTF-8.
- 28 Aug 2003: added Daniel Jönsson’s modifications to use the wrapper in a preloaded library.
- 5 July 2002: featured on !
- 14 Jun 2001: created this document after having added gprof support into .