#include <iostream>
#include <chrono>
template<typename TimeT = std::chrono::milliseconds>
struct measure
{
template<typename F, typename ...Args>
static typename TimeT::rep execution(F func, Args&&... args)
{
auto start = std::chrono::system_clock::now();
// Now call the function with all the parameters you need.
func(std::forward<Args>(args)...);
auto duration = std::chrono::duration_cast< TimeT>
(std::chrono::system_clock::now() - start);
return duration.count();
}
};
struct functor
{
int state;
functor(int state) : state(state) {}
void operator()() const
{
std::cout << "In functor run for ";
}
};
void func()
{
std::cout << "In function, run for ";
}
int main()
{
int dummy(3);
std::cout << measure<std::chrono::nanoseconds>::execution( [&dummy]()
{
dummy *= 2; // usage with lambdas
std::cout << "In lambda, run for ";
}) << std::endl;
std::cout << measure<std::chrono::nanoseconds>::execution(functor(dummy)) << std::endl;
std::cout << measure<std::chrono::nanoseconds>::execution(func);
return 0;
}
I2luY2x1ZGUgPGlvc3RyZWFtPgojaW5jbHVkZSA8Y2hyb25vPgoKCnRlbXBsYXRlPHR5cGVuYW1lIFRpbWVUID0gc3RkOjpjaHJvbm86Om1pbGxpc2Vjb25kcz4Kc3RydWN0IG1lYXN1cmUKewogICAgdGVtcGxhdGU8dHlwZW5hbWUgRiwgdHlwZW5hbWUgLi4uQXJncz4KICAgIHN0YXRpYyB0eXBlbmFtZSBUaW1lVDo6cmVwIGV4ZWN1dGlvbihGIGZ1bmMsIEFyZ3MmJi4uLiBhcmdzKQogICAgewogICAgICAgIGF1dG8gc3RhcnQgPSBzdGQ6OmNocm9ubzo6c3lzdGVtX2Nsb2NrOjpub3coKTsKCiAgICAgICAgLy8gTm93IGNhbGwgdGhlIGZ1bmN0aW9uIHdpdGggYWxsIHRoZSBwYXJhbWV0ZXJzIHlvdSBuZWVkLgogICAgICAgIGZ1bmMoc3RkOjpmb3J3YXJkPEFyZ3M+KGFyZ3MpLi4uKTsKCiAgICAgICAgYXV0byBkdXJhdGlvbiA9IHN0ZDo6Y2hyb25vOjpkdXJhdGlvbl9jYXN0PCBUaW1lVD4gCiAgICAgICAgICAgIC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