Friday, February 19, 2010

Profiling on Mac OSX with Saturn

It is always advisable to profile your code before trying to optimize it. It is often most helpful to role your own (using timers & counters), but often a quick and simple tool will help a lot.

For windows I like the very sleepy profiler. On Mac OSX Apple provide the Saturn profiler (See: Saturn profiler user guide).

To demonstrate we can try compiling a small program:
#include <math.h> 
#include <stdio.h> 

#include <saturn.h> //include the saturn profiler

double func1(double x) { //do some maths
    return sin(x)*cos(x); 

double func2(double x) { //do some more maths
    return pow(x,3); 

int main() { 
    double x=0; 
    double z=0; 
    startSaturn(); //being profiling 
    for (x=0;x<100;x+=0.01) {
    stopSaturn(); //end profiling 
    printf("z:%f\n",z); //make sure compiler doesn't throw our computations away
    return 0; 

Now we need to compile it with profiling support:
g++ x.c -finstrument-functions -lSaturn -m32 -O2

Some common problems include:

  • Undefined symbols: ___cyg_profile_func_enter
    This comes from the -finstrument-functions option : it requires a special hook for each function - this is provided by saturn, so you must link with it.

  • ld: warning: in /usr/lib/libSaturn.dylib, file is not of required architecture
    Undefined symbols: _startSaturn
    Again, either you forgot -lSaturn, or you have remembered it, but are using a 64 bit OS/chip. Specify '-m32' to force 32bit mode.

If it all compiled succesfully, then start Saturn and choose 'Saturn', 'Launch Process'. Then select the executable (eg: a.out) in the dialog box.

Press OK, and Saturn will run and profile your program, and generate a folder with the profiler output data. (eg: Saturn_profile_a.out.000)

You can then select the data file to view the output, and Saturn will display a call graph and the amount of time spent in each function. Now the fun of optimizing can begin. Enjoy!


pppp said...

Thank you for your guide -- it saved me a lot of time with -m32 flag...

JP said...

Thanks for the excellent guide, although sadly it makes it evident that Saturn is mostly useless. For example, without x86_64 support, it cannot be linked to open source libraries that you've compiled purposefully as x86_64.

Tarek said...

Thank you, the -m32 flag saved me a lot of time