Friday 15 April 2011

Function profilers

Hving written your magnus opus that does everything as well as making tea for the head trader of investment bank XYZ you get a complaint that the code runs as dog, and he wants it fixed or the project is binned.  It can though be a nightmare in finding those areas of code that could provide that factor of 10 improvement that you are looking for.  Well it is time to get out your profiler.  The ones that I have used have been extremly complicated use and so I wrote my own.
#include "function_profiler.h"
 
 #define USE_PROFILING
 
 int main()
 {
 #ifdef USE_PROFILING
   xt::stack_time stack_timer;
   PROFILE_FUNCTION();
 #endif
 
 //Scatter these throughout your recursive functions
 PROFILE_FUNCTION();
 do_something_interesting()
 
  {
   PROFILE_FUNCTION1("load_data");
   do_something_even_more_interesting()
  }
 //If you want more than one in a function put them into their own stack space by wrapping them in "{}"s.
 
 #ifdef USE_PROFILING
   stack_timer.print_to_file("Load.xml");
 #endif
 }
Done!  You will now see an xml file that you can load in your browser, and see a structured log of how long each function took to process and a breakdown of each child function.  The code is thread safe and you can have one profiler per thread, just make sure that you give the outputted files different names!
Here is the code core.zip (40.83 kb) there are some other things there which you can ignore or use as you like.  Some of my projects require Roguewave, some can have Boost, this library contains an abstraction layer to support either, e.g. my string class is a std::basic_string<TCHAR> with boost and RWCString in Roguewave.  This includes support for threads, and includes ZThread as well.  And a universal logger which I will explain in a later blog entry.

No comments:

Post a Comment