Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A function to measure time of overloaded operators and member function

Tags:

c++

Description


Is it possible to write a function that can be used to measure the time of operators as well as other functions something like this:
// pass an operator as an argument
measureTime(MyClass::operator*, lhs, rhs);

// Pass a function as an argument
measureTime(MyFunction(arg1, arg2));

// or
measureTime(MyFunction, arg1, arg2);

// or other signatures ...

I came across a function template to do this:

template<typename F, typename... Args>
double measureTime(F func, Args&&... args){
    auto t1 = high_resolution_clock::now();
    func(std::forward<Args>(args)...);
    return high_resolution_clock::now() - t1;
}

Not sure how to use this (or write a new function) to measure the time of overloaded operators.

Questions


  • What is the best way to do this (if possible)?
  • If not possible, what are the other options ?

Example


I'm writing a library for big integer arithmetic, I am using different algorithms and want to measure (and compare) their times (and see their behaviour) when passing different length integers...

This is part of my class:

class bigint {
   public:
      int compare(const bigint& other) const;
      bigint operator*(const bigint& rhs) const;
      bigint& operator++();
      bigint otherAlgorithms(const bigint& other) const;
      // and more ...
}

I also have a lot of input data, and want to pass those data within a for loop and print out the times.

That's why I was looking for a generic function that can printout the times for any function / operator.

like image 418
A-Sharabiani Avatar asked Mar 08 '23 05:03

A-Sharabiani


1 Answers

std::invoke can invoke functions, lambdas and member-functions, so let std::invoke handle the function call:

template<typename... Args>
double measureTime(Args&&... args){
    auto t1 = high_resolution_clock::now();
    std::invoke(std::forward<Args>(args)...);
    return duration(high_resolution_clock::now() - t1);
}

Now you can measure member functions and operators:

struct Test {
    void aFunction() {
        std::cout << "Hello World\n";  
    }

    void operator++() {
        std::cout << "Hello World\n"; 
    }
};
int main()
{
    Test t;
    std::cout << measureTime(&Test::aFunction, t) << "\n";
    std::cout << measureTime(&Test::operator++, t) << "\n";
}

Working Example

Edit: Even though I don't recommend using it, it does look nice:

 #define MEASURE(call) measureTime([&](){ call; })
 std::cout << MEASURE(t.aFunction()) << "\n";

And it allows you to measure more than one function call.

std::cout << MEASURE(t.aFunction(); t.aFunction(); t.aFunction();) << "\n";
like image 79
tkausl Avatar answered Apr 29 '23 12:04

tkausl