Last active
September 13, 2023 08:55
-
-
Save lizhongz/21e77864aa9d5f66e842 to your computer and use it in GitHub Desktop.
C++ decorator measuring the execution time of a function
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <functional> | |
#include <chrono> | |
#include <iostream> | |
template <class> struct ExeTime; | |
// Execution time decorator | |
template <class R, class... Args> | |
struct ExeTime<R(Args ...)> { | |
public: | |
ExeTime(std::function<R(Args...)> func): f_(func) { } | |
R operator ()(Args ... args) { | |
std::chrono::time_point<std::chrono::system_clock> start, end; | |
std::chrono::duration<double> elasped; | |
start = std::chrono::system_clock::now(); | |
R result = f_(args...); | |
end = std::chrono::system_clock::now(); | |
elasped = end - start; | |
std::cout << elasped.count() << " seconds" << std::endl; | |
return result; | |
} | |
private: | |
std::function<R(Args ...)> f_; | |
}; | |
template <class R, class... Args> | |
ExeTime<R(Args ...)> make_decorator(R (*f)(Args ...)) { | |
return ExeTime<R(Args...)>(std::function<R(Args...)>(f)); | |
} | |
// Test function | |
int foo_loop(int n) { | |
long long sum = 0; | |
for (int i = 0; i < n; ++i) { | |
sum += i; | |
} | |
return sum; | |
} | |
int main() { | |
auto et = make_decorator(foo_loop); | |
et(10000000); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment