C++11 std::function 比虚拟调用慢?

标签 c++ performance c++11

我正在创建一种机制,允许用户使用 decorator pattern 从基本构建 block 形成任意复杂函数.这在功能方面工作得很好,但我不喜欢它涉及大量虚拟调用的事实,尤其是当嵌套深度变大时。这让我很担心,因为复杂的函数可能会经常调用(>100.000 次)。

为了避免这个问题,我尝试在完成后将装饰器方案转换为 std::function(参见 SSCCE 中的 to_function())。所有内部函数调用都在std::function 的构造过程中进行连接。我认为这会比原始装饰器方案更快评估,因为在 std::function 版本中不需要执行虚拟查找。

唉,基准测试证明我错了:装饰器方案实际上比我用它构建的 std::function 更快。所以现在我想知道为什么。也许我的测试设置有问题,因为我只使用了两个微不足道的基本功能,这意味着可能会缓存 vtable 查找?

我使用的代码包含在下面,不幸的是它很长。


SSCCE

// sscce.cpp
#include <iostream>
#include <vector>
#include <memory>
#include <functional>
#include <random>

/**
 * Base class for Pipeline scheme (implemented via decorators)
 */
class Pipeline {
protected:
    std::unique_ptr<Pipeline> wrappee;
    Pipeline(std::unique_ptr<Pipeline> wrap)
    :wrappee(std::move(wrap)){}
    Pipeline():wrappee(nullptr){}

public:
    typedef std::function<double(double)> FnSig;
    double operator()(double input) const{
        if(wrappee.get()) input=wrappee->operator()(input);
        return process(input);
    }

    virtual double process(double input) const=0;
    virtual ~Pipeline(){}

    // Returns a std::function which contains the entire Pipeline stack.
    virtual FnSig to_function() const=0;
};

/**
 * CRTP for to_function().
 */
template <class Derived>
class Pipeline_CRTP : public Pipeline{
protected:
    Pipeline_CRTP(const Pipeline_CRTP<Derived> &o):Pipeline(o){}
    Pipeline_CRTP(std::unique_ptr<Pipeline> wrappee)
    :Pipeline(std::move(wrappee)){}
    Pipeline_CRTP():Pipeline(){};
public:
    typedef typename Pipeline::FnSig FnSig;

    FnSig to_function() const override{
        if(Pipeline::wrappee.get()!=nullptr){

            FnSig wrapfun = Pipeline::wrappee->to_function();
            FnSig processfun = std::bind(&Derived::process,
                static_cast<const Derived*>(this),
                std::placeholders::_1);
            FnSig fun = [=](double input){
                return processfun(wrapfun(input));
            };
            return std::move(fun);

        }else{

            FnSig processfun = std::bind(&Derived::process,
                static_cast<const Derived*>(this),
                std::placeholders::_1);
            FnSig fun = [=](double input){
                return processfun(input);
            };
            return std::move(fun);
        }

    }

    virtual ~Pipeline_CRTP(){}
};

/**
 * First concrete derived class: simple scaling.
 */
class Scale: public Pipeline_CRTP<Scale>{
private:
    double scale_;
public:
    Scale(std::unique_ptr<Pipeline> wrap, double scale) // todo move
:Pipeline_CRTP<Scale>(std::move(wrap)),scale_(scale){}
    Scale(double scale):Pipeline_CRTP<Scale>(),scale_(scale){}

    double process(double input) const override{
        return input*scale_;
    }
};

/**
 * Second concrete derived class: offset.
 */
class Offset: public Pipeline_CRTP<Offset>{
private:
    double offset_;
public:
    Offset(std::unique_ptr<Pipeline> wrap, double offset) // todo move
:Pipeline_CRTP<Offset>(std::move(wrap)),offset_(offset){}
    Offset(double offset):Pipeline_CRTP<Offset>(),offset_(offset){}

    double process(double input) const override{
        return input+offset_;
    }
};

int main(){

    // used to make a random function / arguments
    // to prevent gcc from being overly clever
    std::default_random_engine generator;
    auto randint = std::bind(std::uniform_int_distribution<int>(0,1),std::ref(generator));
    auto randdouble = std::bind(std::normal_distribution<double>(0.0,1.0),std::ref(generator));

    // make a complex Pipeline
    std::unique_ptr<Pipeline> pipe(new Scale(randdouble()));
    for(unsigned i=0;i<100;++i){
        if(randint()) pipe=std::move(std::unique_ptr<Pipeline>(new Scale(std::move(pipe),randdouble())));
        else pipe=std::move(std::unique_ptr<Pipeline>(new Offset(std::move(pipe),randdouble())));
    }

    // make a std::function from pipe
    Pipeline::FnSig fun(pipe->to_function());   

    double bla=0.0;
    for(unsigned i=0; i<100000; ++i){
#ifdef USE_FUNCTION
        // takes 110 ms on average
        bla+=fun(bla);
#else
        // takes 60 ms on average
        bla+=pipe->operator()(bla);
#endif
    }   
    std::cout << bla << std::endl;
}

基准测试

使用管道:

g++ -std=gnu++11 sscce.cpp -march=native -O3
sudo nice -3 /usr/bin/time ./a.out
-> 60 ms

使用乐趣:

g++ -DUSE_FUNCTION -std=gnu++11 sscce.cpp -march=native -O3
sudo nice -3 /usr/bin/time ./a.out
-> 110 ms

最佳答案

你有 std::functions 绑定(bind) lambdas 调用 std::functions 绑定(bind) lamdbas 调用 std::functions那……

查看您的 to_function。它创建一个调用两个 std::function 的 lambda,并将绑定(bind)到另一个 std::function 的 lambda 返回。编译器不会静态解析任何

所以最后,你会得到与虚函数解决方案一样多的间接调用,那就是如果你摆脱绑定(bind)的 processfun 并直接在 lambda 中调用它。否则你有两倍多。

如果你想要加速,你必须以一种可以静态解析的方式创建整个管道,这意味着在你最终将类型删除到单个 std::function 之前需要更多的模板.

关于C++11 std::function 比虚拟调用慢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18608888/

相关文章:

c++ - C++ 中的多个异步调用

c++ - 使用 OLE 以编程方式保存 Excel 文件

python - 为什么 python 程序在 mac os 终端中运行速度比在虚拟机(ubuntu)中慢?

c++ - 为容器中的不同字符串类型实现编译时 "static-if"逻辑

c++ - 经过最后一个数组元素末尾的指针是否等于经过整个数组末尾的指针?

c++ - C++类中的内存泄漏

c++ - C++ 枚举使用起来比整数慢吗?

mysql - 非常慢的 TRUNCATE 伴随着 httpd 日志上的 "Server seems busy"

c++ - 指向成员的指针,在类中

c++ - 将双指针作为参数传递给需要引用 std::vector<double> 的函数