C++:幾種callable實現方式的性能對比


C++中幾種callable實現方式的性能對比

前言

C++中想實現一個callable的對象,通常有四種方式:

  1. std::function:最common的方式,一般會配合std::bind使用。
  2. function pointer:最C的方式,但沒辦法實現有狀態的callable object。
  3. function object:就是重載了operator()的類,C++98的STL中經常用。
  4. lambda expression:不會污染namespace,一般來說編譯器內部會實現為一個匿名的function object。

從原理上性能最好的應該是3和4,其次是2,最差的是std::function。下面我們用一小段代碼來測試它們的性能。

測試結果

  • 測試機器:15' rMBP。
  • 編譯器:Apple LLVM version 8.1.0 (clang-802.0.42)。
  • 編譯方式:g++ test.cpp -std=c++14 -O2。
./a.out "std::function"  0.15s user 0.20s system 98% cpu 0.358 total
./a.out "function_pointer"  0.10s user 0.11s system 98% cpu 0.209 total
./a.out "function_object"  0.03s user 0.01s system 92% cpu 0.042 total
./a.out "lambda"  0.03s user 0.01s system 93% cpu 0.042 total

可以看到3和4只要42ms,而相對應的2需要209ms,1需要358ms。這個順序符合我們的預期,但相差這么多還是比較意外的。

測試程序

#include <iostream>
#include <functional>
#include <vector>
#include <string>
#include <utility>

using namespace std;

template <typename HandlerT = std::function<void (int)>>
class Worker{
public:
    explicit Worker(const HandlerT& handler): mHandler(handler) {}
    void Run(int x) {
        mHandler(x);
    }
private:
    HandlerT mHandler;
};

template <typename HandlerT>
void Test(HandlerT&& h) {
    using WorkerT = Worker<HandlerT>;
    vector<WorkerT> v;
    for (int i = 0; i < 10000000; ++i) {
        v.emplace_back(std::forward<HandlerT>(h));
    }
    int j = 0;
    for (auto& w: v) {
        w.Run(++j);
    }
}

void Func(int x) {
    int y = x + 5;
    y += 3;
}

struct Functor {
    void operator()(int x) const {
        int y = x + 5;
        y += 3;
    }
};

int main(int argc, char** argv) {
    if (argc != 2) {
        cerr << "error input" << endl;
        exit(1);
    }

    string mode{argv[1]};
    if (mode == "std::function") {
        Test(bind(Func, placeholders::_1));
    } else if (mode == "function_pointer") {
        Test(Func);
    } else if (mode == "function_object") {
        Test(Functor{});
    } else if (mode == "lambda") {
        Test([](int x) -> void {int y = x + 5; y += 3;});
    } else {
        cerr << "error mode:" << mode << endl;
        exit(1);
    }
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM