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 forpthread_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):
/* gprof-helper.c -- preload library to profile pthread-enabled programs |