用于测量重载运算符和成员函数的时间的函数

时间:2017-08-24 23:54:16

标签: c++

描述

<小时/> 是否可以编写一个可用于测量运算符时间的函数以及其他函数:

// 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 ...

我遇到了一个功能模板来执行此操作:

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;
}

不确定如何使用它(或编写新函数)来测量重载运算符的时间。

问题

  • 最好的方法是什么(如果可能的话)?
  • 如果不可能,还有其他选择吗?

示例

<小时/> 我正在编写一个用于大整数运算的库,我正在使用不同的算法,并希望在传递不同长度的整数时测量(和比较)它们的时间(并查看它们的行为)...... < p>

这是我班级的一部分:

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 ...
}

我还有很多输入数据,并希望在for循环内传递这些数据并打印出来。

这就是为什么我在寻找可以打印任何函数/运算符时间的通用函数。

1 个答案:

答案 0 :(得分:6)

std::invoke可以调用函数,lambdas和成员函数,所以让std::invoke处理函数调用:

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);
}

现在您可以测量成员函数和运算符:

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

编辑: 即使我不建议使用它,它看起来确实很好:

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

它允许您测量多个函数调用。

std::cout << MEASURE(t.aFunction(); t.aFunction(); t.aFunction();) << "\n";