Skip to content

Instantly share code, notes, and snippets.

@deysumitkr
Last active November 5, 2019 15:56
Show Gist options
  • Save deysumitkr/cffb930868658cc214c135a1c2228774 to your computer and use it in GitHub Desktop.
Save deysumitkr/cffb930868658cc214c135a1c2228774 to your computer and use it in GitHub Desktop.
Execution time of a code snippet
#include <chrono>
#include <utility>
/**
* @brief find execution time of a function with non-void return type
*
* @tparam F function signature in form return_type(args...). Eg: double(int, int, char*)
* @tparam R set clock resolution from chrono clock (default = std::chrono::microseconds)
* @tparam Args varidac typenames for function arguments
* @param dt execution time as per resolution given in R
* @param func function to time
* @param args function arguments
* @return auto function return type deduced from function signature
*/
template<typename F, typename R = std::chrono::microseconds, typename... Args>
auto funcTimer(double & dt, std::function<F> func, Args&&... args) {
auto start = std::chrono::steady_clock::now();
auto retval = func(std::forward<Args>(args)...);
auto end = std::chrono::steady_clock::now();
auto diff = end - start;
dt = std::chrono::duration_cast <R> (diff).count();
return retval;
}
// -----------------------------------------
// Usage
double ms;
std::function<int(int, int)> fp = std::bind(&SomeClass::member_function, obj_of_SomeClass, std::placeholders::_1, std::placeholders::_2);
int retval = utils::funcTimer<int(int, int), std::chrono::milliseconds>(ms, fp, 800, 600);
// ms will hold the execution duration in milliseconds
/** using chrono **/
#include <chrono>
auto start = std::chrono::high_resolution_clock::now();
// Code to time
auto finish = std::chrono::high_resolution_clock::now();
double duration = std::chrono::duration_cast<std::chrono::milliseconds>(finish - start).count();
/** using clock **/
#include <time.h>
clock_t start, end;
start = clock();
// Code to time
end = clock();
double duration = (((double) (end - start)) / CLOCKS_PER_SEC) * (double)1e+06; // microseconds
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment