Skip to content

Instantly share code, notes, and snippets.

@agustingianni
Created October 22, 2016 22:44
Show Gist options
  • Select an option

  • Save agustingianni/dfb3d134b04b89b03fa2891367afd45a to your computer and use it in GitHub Desktop.

Select an option

Save agustingianni/dfb3d134b04b89b03fa2891367afd45a to your computer and use it in GitHub Desktop.
// Small utility to measure how much time does it take to
// run an arbitrary function.
// Written by Agustin Gianni (agustin.gianni@gmail.com).
// Based on https://ngathanasiou.wordpress.com/2015/04/01/benchmarking-in-c/
//
// $ clang++ measure.cpp -o measure -std=c++11 -Wall && ./measure
// Return value: Boom!
// Elapsed time: 0 ms
#include <ctime>
#include <chrono>
#include <string>
#include <iostream>
// Measure the time it takes to execute a given function.
template<typename time_type=std::chrono::milliseconds, typename clock=std::chrono::steady_clock>
struct measure {
template<typename F, typename ...Args>
static std::pair<typename std::result_of<F(Args...)>::type, typename time_type::rep> execution(F func, Args&&... args) {
auto t0 = clock::now();
auto ret = func(std::forward<Args>(args)...);
auto t1 = clock::now();
auto delta = std::chrono::duration_cast<time_type>(t1 - t0);
return std::make_pair(ret, delta.count());
}
};
static std::string test() {
return "Boom!";
}
int main(int argc, char **argv) {
auto ret_pair = measure<>::execution(test);
std::cout << "Return value: " << ret_pair.first << '\n';
std::cout << "Elapsed time: " << ret_pair.second << " ms\n";
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment