Wednesday 14 October 2015

Timing a function

Some time ago, I started practising Codility tests.
While I believe they cannot be the only way to evaluate a good developer, Codility tests propose fairly interesting programming tasks to keep your mind fit.
Since usually, the task asks you to implement a function that solves the problem in a certain level of complexity indicated with the big-O notation, you will need to find a way to measure the performance of your code.

I created a Visual Studio C++ solution including all the Codility problems and their solutions.
For each class that implements a particular problem, the main function calls the method solution() and measures it.

To avoid repeating the code for measuring the execution time, I thought to use a generic approach.
The idea was to pass a functor to another function that executes the functor and evaluates the total elapsed time. In C++, this can be done by writing a template function.
This is the code of the function:

  template<typename Function>
  inline static float timeFunction(Function f)
  {
    clock_t t = clock();
    f();
    t = clock() - t;
    return ((float)t) / CLOCKS_PER_SEC;
  };


Where Function is the generic type of the argument.
I can, therefore, pass a lambda expression to timeFunction:

float elapsed = timeFunction([](){ function_to_be_timed(); }); 


Here is another version that makes use the Windows high-resolution timer:

  template<typename Function>
  inline static double timeFunctionMicroSec(Function f)
  {
    LARGE_INTEGER StartingTime, EndingTime, ElapsedMicroseconds;
    LARGE_INTEGER Frequency;

    QueryPerformanceFrequency(&Frequency);
    QueryPerformanceCounter(&StartingTime);

    f();

    QueryPerformanceCounter(&EndingTime);
    ElapsedMicroseconds.QuadPart = EndingTime.QuadPart - StartingTime.QuadPart;
    ElapsedMicroseconds.QuadPart *= 1000000;
    ElapsedMicroseconds.QuadPart /= Frequency.QuadPart;

    return double(ElapsedMicroseconds.QuadPart);
  };


I hope this will be useful to you.