I needed a way how to measure the execution time of a function. I found this very good answer on SO https://stackoverflow.com/a/21995693/3179492. It is a perfect solution.
It is using a function pointer with variadic parameters list.
Here is the MCVE:
#include <algorithm>
#include <chrono>
#include <stdio.h>
class Foo
{
public:
auto foo_member( int x ) -> void { printf( "in foo_member(%d);\n", x ); }
};
class measure
{
public:
template<typename F, typename ...Args>
static typename std::chrono::microseconds::rep execution(F func, Args&&... args)
{
auto start = std::chrono::system_clock::now();
func(std::forward<Args>(args)...);
auto duration = std::chrono::duration_cast<std::chrono::microseconds>
(std::chrono::system_clock::now() - start);
return duration.count();
}
};
int main()
{
Foo foo;
int x = 1234;
// this line does not compile
printf( "execution time=%ld\n", measure::execution( foo.foo_member, x ) );
}
This code does not compile because foo_member
is not static. The error message is invalid use of non-static member function
.
There are few ways how to resolve the problem. For me, the most elegant, shortest and effective way is this:
printf("execution time=%ld\n", measure::execution( [&foo, &x] () { foo.foo_member(x); } ));
This means, I use a lambda function in order to get the line compiled.
I am just wondering why the compiler could not do it for me? The code path is exactly defined how to translate the first version into a lambda function using the capture mechanism. When you just realize what a modern c++ compiler is doing with the code this would be indeed one of the simplest code reordering...
Note:
It is compiled with these gcc
flags: -Wall -Werror -Wextra -std=c++11