衡量 std::function 的性能成本

rob*_*986 2 c++ performance c++11

我正在尝试衡量 std::function 与 C-Function 指针的性能成本。我想知道我的测量技术对于这个特定函数是否公平(分贝,见下文)。

为了测试以下测量,我重新编译了 N 1 到 6 的程序(见下文)并切换了注释的 std::function 与原始函数指针。

代码:

#include<iostream>
#include<thread>

typedef float (*twoArgFuncPtr)(float, float);

//function name and signature
typedef float (*twoArgFuncPtr)(float, float);   
//a function matching the signature of the typedef function
float decibels(float p1, float p2)  
{
    return (float)log(p2 / p1);
}
int main()
{
    typedef std::chrono::high_resolution_clock high_resolution_clock;
    typedef std::chrono::milliseconds milliseconds;
    twoArgFuncPtr fnc= decibels;
    std::function<float(float,float)> fncObj= decibels;
    const int numLoops= 1000000*1; //re-compiled for 1000000 * to N=6
    high_resolution_clock::time_point start= high_resolution_clock::now();
    float result=0;
    for(int i=1, j=numLoops; i < numLoops-1; i++, j--)
    {
        //toggle the comment between the next two lines
        result+= fnc((float)i, (float)j);       //call by raw ptr
        //result+= fncObj((float)i, (float)j); //call by obj //uncomment this line to test std::function
    }
    high_resolution_clock::time_point end= high_resolution_clock::now();
    std::cout<<"Time in seconds: "<<std::chrono::duration_cast<milliseconds>(end-start).count()<<std::endl;
    std::cout<<"Result: "<<result<<std::endl;
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

我得到以下时间:

在此处输入图片说明

平均而言,原始函数指针比 std::function 快 2.6 倍。我的时间对 std::function 还是原始 func ptr 公平吗?

编辑:我关闭了优化 Compiled with Visual Studio 2012 Core i5 windows server 64bit

编辑#2:我为每个请求提供完整的优化时间: 在此处输入图片说明

谢谢!

Yak*_*ont 6

优化后的版本对std::function.

std::function典型的实现是一个类型擦除的 pImpl 内部类,它有一个virtual调用和复制接口。

这意味着调用 a 的成本std::function大致是virtual方法调用加上原始调用的成本。

理论上std::function可以优化指针到相同签名函数的情况(以及用于包装函数指针的 tyoe 转换的函数指针到函数指针的情况)。

std::function如果virtual方法表不在缓存中,则会产生额外的重大影响。这在您的测试中不太可能发生,但在实际的实际用例中很可能发生。因此不仅仅是公平。