Tuesday, November 4, 2014

Simple macro for measuring algorithm's running time

Recently I'm spending a lot of time on my master's thesis. I'm working on algorithm for automatic number plates recognition using image segmentation. I'm trying to achieve high performance, so I need to measure execution time of my algorithms.
A few weeks ago I've written about google benchmark [1]. It's quite powerful library, and it's easy to use even in simple case, but sometimes we don't want to depend on an external library. So is it in my case too.
I've created simple macro for measuring running time:
#include <chrono>

#define MEASURE_TIME(unit, ...)    \
  [&] {         \
    using namespace std::chrono;     \
    auto start = high_resolution_clock::now ();    \
    __VA_ARGS__;       \
    auto time = high_resolution_clock::now () - start;   \
    return duration_cast<unit> (time).count ();    \
  } ();


Arguments:
  • unit - std::chrono::duration time interval. You can simply pass defined in standard library types, e.g. predefined types:
    • std::chrono::nanoseconds
    • std::chrono::microseconds
    • std::chrono::milliseconds
    • std::chrono::seconds
    • std::chrono::minutes
    • std::chrono::hours
  • ... - code for measurement
And example usage:
  int value = 0;

  auto duration = MEASURE_TIME(std::chrono::milliseconds, 
    int arg0, arg1;
    arg0 = run_time_consuming_algorithm ();
    arg1 = run_another_one(arg0);
    value = run_third_algorithm(arg1);
  );

  cout << "Execution time: " << duration << std::endl
       << "Computed value: " << value;

Note, that you can use earlier declared values (value variable, in my case), because all the values are captured by reference in lambda.

Feel free to use it ;)

Links
[1] http://cookandcommit.blogspot.com/2014/09/tiny-c-benchmark-framework_29.html 

No comments:

Post a Comment