Last active
October 25, 2021 01:45
-
-
Save micjabbour/f8b98997a76bd7e6e83642182516b3a9 to your computer and use it in GitHub Desktop.
C++ time profiling example
This file contains hidden or 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
//from Howard Hinnant's answer https://stackoverflow.com/a/18303787 | |
#include <random> | |
#include <chrono> | |
#include <iostream> | |
std::random_device eng; //can be used to generate random input for test cases | |
std::uniform_int_distribution<std::size_t> random(500, 1000); | |
//a function template that executes a given function object and returns | |
//its execution time | |
template<typename Func> | |
std::chrono::high_resolution_clock::duration getExecutionTime(Func&& f) | |
{ | |
auto t0 = std::chrono::high_resolution_clock::now(); | |
f(); | |
auto t1 = std::chrono::high_resolution_clock::now(); | |
return t1 - t0; | |
} | |
int main() | |
{ | |
const int n = 10000; //number of iterations | |
using nano = std::chrono::duration<double, std::nano>; | |
nano ns(0); | |
for (int i = 0; i < n; ++i) { //n iterations | |
//TODO: setup test paramaters. random numbers can be generated by e.g. | |
//int size = random(eng); | |
ns += getExecutionTime([&](){ //capture test parameters by reference | |
//TODO: do whatever you want to profile here | |
}); | |
} | |
ns /= n; | |
std::cout << "average execution time: " << ns.count() << " ns\n"; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment