Skip to content

Instantly share code, notes, and snippets.

@nurettin
Created November 15, 2013 12:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nurettin/7483287 to your computer and use it in GitHub Desktop.
Save nurettin/7483287 to your computer and use it in GitHub Desktop.
pretty benchmark class
// 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