Created
November 15, 2013 12:01
-
-
Save nurettin/7483287 to your computer and use it in GitHub Desktop.
pretty benchmark class
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
// the idea is to benchmark and output pretty results | |
#include <iostream> | |
#include <functional> | |
#include <chrono> | |
#include <vector> | |
struct Fun | |
{ | |
std::string name; | |
std::function<void()> fun; | |
Fun(std::string const &name, std::function<void()> fun) | |
: name(name) | |
, fun(fun) | |
{} | |
}; | |
struct Bm | |
{ | |
std::vector<Fun> funs; | |
void bench(Fun const &fun) | |
{ | |
funs.push_back(fun); | |
} | |
template<typename... Args> | |
typename std::enable_if<std::is_constructible<Fun, Args...>::value>::type bench(Args&& ...args) | |
{ | |
bench({std::forward<Args>(args)...}); | |
} | |
std::chrono::milliseconds run(std::ostream &o= std::cout) | |
{ | |
using namespace std::chrono; | |
milliseconds total(0); | |
for(auto &fun: funs) | |
{ | |
o<< fun.name<< ": "; | |
auto t= high_resolution_clock::now(); | |
fun.fun(); | |
auto d= duration_cast<milliseconds>(high_resolution_clock::now()- t); | |
o<< d.count()<< "ms\n"; | |
total+= d; | |
} | |
o<< "total: "<< total.count()<< "ms\n"; | |
return total; | |
} | |
}; | |
int main() | |
{ | |
Bm bm; | |
bm.bench("f1", [](){ | |
for(uint64_t i= 0; i< 100000000; ++ i); | |
}); | |
bm.bench("f2", [](){ | |
for(uint64_t i= 100000000; i--;); | |
}); | |
bm.run(std::cout); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment