10 Sep 2013

When working as a programmer there are tasks or small problems that tend to reoccur from time to time. One of these problems is to provide a way of measuring how much time a piece of code takes.

For this logic I tend to either use profiling tools, but creating an abstraction for measuring time explicitly is also necessary because of the overhead introduced by almost all profiling tools.

Since I am currently writing C++ code I will solve the problem using C++ and the C++11 standard. The abstraction I have created here is called a StopWatch it is basically a thin wrapper around logic for starting and stopping a timer.

#include <chrono>

using namespace std::chrono;

class StopWatch
  system_clock::time_point begin;
  system_clock::time_point end;

  void start() 
    begin = system_clock::now();

  void stop()
    end = system_clock::now();    

  int result()
    milliseconds ms = duration_cast<milliseconds>(end - begin);
    return ms.count();

That's it, it doesn't need to be any more code. The only thing that is a bit complex with this code is the way the chrono library works. I should explain that in more detail in another note, but not right now. This should be all you need to start analyzing some code paths.