patterncppMajor
Measuring execution time in C++
Viewed 0 times
timeexecutionmeasuring
Problem
I had time measuring pretty much figured out when I ended up using this structure.
a use case would be
But since I started using my struct in various posts on Stack Exchange sites, I've had remarks and comments about the code (like on
I'd like a review on the above and your suggestions on how I can approve this code (or leave it alone at last).
#include
#include
template
struct measure
{
template
static typename TimeT::rep execution(F const &func)
{
auto start = std::chrono::system_clock::now();
func();
auto duration = std::chrono::duration_cast(
std::chrono::system_clock::now() - start);
return duration.count();
}
};a use case would be
struct functor
{
int state;
functor(int state) : state(state) {}
void operator()() const
{
std::cout ::execution( [&]() {
func(dummy);
}) ::execution(functor(dummy)) ::execution(func);
return 0;
}But since I started using my struct in various posts on Stack Exchange sites, I've had remarks and comments about the code (like on
func being a const ref or not etc). I'd like a review on the above and your suggestions on how I can approve this code (or leave it alone at last).
Solution
- Extend your timer function so it can take all the parameters needed by
func()
- Don bother to pass
funcby const reference.
What I would have done
template
struct measure
{
template
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)...);
auto duration = std::chrono::duration_cast(std::chrono::system_clock::now() - start);
return duration.count();
}
};Code Snippets
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();
}
};Context
StackExchange Code Review Q#48872, answer score: 21
Revisions (0)
No revisions yet.