0

I am trying to build a wrapper that measures execution time of functions and methods, that should be as close as possible to a drop-in replacement. At the moment, I am doing

template<typename Return, typename... Params>  auto measure_time(Return (*f)(Params...)){
    struct Wrapper {
        Return operator()(Params... params){
            using std::chrono::steady_clock;
            using std::chrono::duration_cast;
            using std::chrono::milliseconds;

            steady_clock::time_point begin = steady_clock::now();
            Return result = (*f)(std::forward<Params>(params)...);
            steady_clock::time_point end = steady_clock::now();
            std::cout << duration_cast<milliseconds>(end - begin).count() << "ms" << std::endl;
            return result;
        }
        Return (*f)(Params...);
    };
    return Wrapper{f};
}

for functions (and similarly for objects with methods). However, if

int f(int i=0){
   return i;
}

has a default argument, calling

measure_time(f)();

wont work; instead, I really have to provide a value for i: measure_time(f)(1). Can this be resolved?

Bubaya
  • 615
  • 3
  • 13
  • 2
    With a small adjustment of `measure_time`, you could wrap it into a lambda: `measure_time([]{ f(); })();`. – Evg May 05 '22 at 07:53
  • 3
    Default function arguments are not part of a function's signature. Evg's proposal of wrapping into a lambda is a good approach. See also e.g. [Measure execution time of arbitrary functions with C++14 lambda](https://stackoverflow.com/questions/53738032) (possibly a dupe target for this question). – dfrib May 05 '22 at 08:52

0 Answers0