You can abstract the time measuring mechanism and has each callable's run time measured with minimal extra C Ode, just by being called through a timer structure. Plus, at compile time you can parametrize the timing type (milliseconds, nanoseconds etc). Thanks to the review by Loki Astari and the suggestion to use variadic templates. The forwarded function call. #include <iostream>#include <chrono>Template<TypeName TimeT =Std::Chrono::Milliseconds>structMeasure{ Template<TypeNameF, TypeName ...Args> Static TypeName TimeT::Rep execution(F&&Func, Args&&, .....Args) { AutoStart=Std::Chrono::Steady_clock::Now();Std::Forward<Decltype(Func) > (Func)(Std::Forward<Args> (Args)...); AutoDuration=Std::Chrono::Duration_cast< TimeT> (Std::Chrono::Steady_clock::Now() -Start); return Duration.}};int Main () { Std::cout <<<>::execution (functor< Span class= "pun" > (dummy << Std::endl; /span>
Demo According to the comment by Howard Hinnant It's best don't to escape out of the the Chrono system until we had to. The above class could give the user the choice to call count manually by providing a extra static method (shown in C + + 14) Template<TypeNameF, TypeName ...Args>Static AutoDuration(F&&Func, Args&&, .....Args){ AutoStart=Std::Chrono::Steady_clock::Now();Std::Forward<Decltype(Func) > (Func)(Std::Forward<Args> (Args)...); ReturnStd::Chrono::Duration_cast<TimeT> (Std::Chrono::Steady_clock::now ()-start); } //call. Count () Manually later when needed (eg IO) auto avg = (measure<>::duration ( Func + Measure< >::duration (func / 2.0
and is most useful for clients that
"Want to post-process a bunch of durations prior to I/O (e.g. average)"
The complete code can is foundhere. My attempt to build a benchmarking tool based on Chrono are recorded here. If c++17 ' s std::invoke is available, the invocation of the callable in could was done like this execution : invoke(forward<decltype(func)>(func), forward<Args>(args)...);
To provide for callables that is pointers to member functions. |