Description
// 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
Example
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.
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";
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With