Performance of std::function compared to raw function pointer and void* this?

前端 未结 3 1966
心在旅途
心在旅途 2020-12-09 19:25

Library code:

class Resource 
{
public:
    typedef void (*func_sig)(int, char, double, void*);
//Registration
    registerCallback(void* app_obj, func_sig f         


        
3条回答
  •  悲哀的现实
    2020-12-09 19:56

    I run a quick benchmark using Google Benchmark Those are the results:

    Run on (4 X 2712 MHz CPU s)
    ----------------------------------------------------------
    Benchmark                   Time           CPU Iterations
    ----------------------------------------------------------
    RawFunctionPointer         11 ns         11 ns   56000000
    StdBind                    12 ns         12 ns   64000000
    StdFunction                11 ns         11 ns   56000000
    Lambda                      9 ns          9 ns   64000000
    

    It seems that the most optimal solution is using lambdas (just like user christianparpart mentioned in this thread). The code I used for benchmark can be found below.

    #include 
    
    #include 
    #include 
    #include 
    
    static volatile int global_var = 0;
    
    void my_int_func(int x)
    {
        global_var = x + x + 3;
        benchmark::DoNotOptimize(global_var);
        benchmark::DoNotOptimize(x);
    }
    
    static void RawFunctionPointer(benchmark::State &state)
    {
        void (*bar)(int) = &my_int_func;
        srand (time(nullptr));
        for (auto _ : state)
        {
            bar(rand());
            benchmark::DoNotOptimize(my_int_func);
            benchmark::DoNotOptimize(bar);
        }
    }
    
    static void StdFunction(benchmark::State &state)
    {
        std::function bar = my_int_func;
        srand (time(nullptr));
        for (auto _ : state)
        {
            bar(rand());
            benchmark::DoNotOptimize(my_int_func);
            benchmark::DoNotOptimize(bar);
        }
    }
    
    static void StdBind(benchmark::State &state)
    {
        auto bar = std::bind(my_int_func, std::placeholders::_1);
        srand (time(nullptr));
        for (auto _ : state)
        {
            bar(rand());
            benchmark::DoNotOptimize(my_int_func);
            benchmark::DoNotOptimize(bar);
        }
    }
    
    static void Lambda(benchmark::State &state)
    {
        auto bar = [](int x) {
            global_var = x + x + 3;
            benchmark::DoNotOptimize(global_var);
            benchmark::DoNotOptimize(x);
        };
        srand (time(nullptr));
        for (auto _ : state)
        {
            bar(rand());
            benchmark::DoNotOptimize(my_int_func);
            benchmark::DoNotOptimize(bar);
        }
    }
    
    
    BENCHMARK(RawFunctionPointer);
    BENCHMARK(StdBind);
    BENCHMARK(StdFunction);
    BENCHMARK(Lambda);
    
    BENCHMARK_MAIN();
    

提交回复
热议问题