2017-08-24 27 views
3

说明 测量重载操作的时间和成员函数的函数


是否有可能编写可被用于测量操作者的其它功能的时间,以及是这样的函数:

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

不知道如何使用这个(或写一个新的函数)来衡量超载运营商的时间。

问题


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


我写的大整数运算库,我使用不同的算法和想测量(和比较)的时间(看看他们的行为)通过不同长度的整数时, ...

这是我的课的一部分:

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

如果使用'的std :: invoke'而不是自己这个调用该函数应与成员的工作职能 - – tkausl

+1

除非'MyFunc'返回一个函数,传递'MyFunction的(ARG1,ARG2)'将结果传递表达式 – Vivick

+0

运算符仍然是一个函数,所以传递它应该没有问题。像'运营商<<(a,b)' – AndyG

回答

6

std::invoke可以调用功能,lambda表达式和成员函数,所以让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"; 
+0

感谢您的回答。更具体地说,这是我的运算符的签名:'bigint运算符*(const bigint&rhs)const'。 (它有争论)。 –

+2

您可以在函数和类实例之后传递参数,即'measureTime(&bigint :: operator *,bigint1,bigint2);'其中'bigint1'是成员被调用的实例(它的''this'函数),'bigint2'是参数。 – tkausl