现在的位置: 首页 > 综合 > 正文

C++ Pirate: Lambda vs Bind  C++ Pirate: Lambda vs Bind

2017年11月03日 ⁄ 综合 ⁄ 共 15630字 ⁄ 字号 评论关闭
 

[置顶] C++ Pirate: Lambda vs Bind

分类: c++ 11 365人阅读 评论(0) 收藏 举报

Lambda 与 Bind的性能比较

转载请说明出处:http://blog.csdn.net/cywosp/article/details/9379403

先让我们看看下面函数:

  1. template <typename Function>  
  2. void do_test_loop(Function func, const uint64_t upper_limit = 1000000000ULL)  
  3. {  
  4.     for (uint64_t i = 0; i < upper_limit; ++i)  
  5.         func(i);  
  6. }  

    该函数只是简单对func函数做upper_limit(默认10亿次)次循环调用。有很多种方法给被反复调用的函数func传入实际参数,在这里我们只讨论两种:
    1. 使用std::bind来生成一个多态的std::function<void (uint64_t)>函数。
    2.lambda表达式
  1. void test_accumulate_bind_function(uint64_t& x, uint64_t i)  
  2. {  
  3.     x += i;  
  4. }  
  5.   
  6. uint64_t test_accumulate_bind()  
  7. {  
  8.     namespace arg = std::placeholders;  
  9.       
  10.     uint64_t x = 0;  
  11.     std::function<void (uint64_t)> accumulator = std::bind(&test_accumulate_bind_function, std::ref(x), arg::_1);  
  12.     do_test_loop(accumulator);  
  13.     return x;  
  14. }  
    这是一个简单的函数,在使用boost::bind函数时,我所遇到的最大的问题是它需要你将函数和逻辑分离,这样会导致难以理解的代码。对比较大的函数来说,这并不是什么大问题,但是对于小函数来说运行时的上下文切换将会很耗时(令人讨厌),例如上面所列举的函数。
    与上述函数相同的lambda表达式如下:   
  1. uint64_t test_accumulate_lambda()  
  2. {  
  3.     uint64_t x = 0;  
  4.     auto accumulator = [&x] (uint64_t i) { x += i; };  
  5.     do_test_loop(accumulator);  
  6.     return x;  
  7. }  

    lambda表达式没有运行时的上下文切换。当然,我们也因此失去了std::function所具有的高级的多态特性。lambda是一种由编译器静态关联的无名类型,这也是为什么在定义该类型时必须使用auto关键字的原因。变量accumulator表示lambda表达式的结果(没有其他的lambda表达式能生成与此一样的结果)。即使是两个内容差不多的表达式也不会有相同的类型。如果do_test_loop是一个在cpp文件中实现的函数,那么我们将在其的作用域范围内获取不到传入进来的lambda表达式类型。 幸运的是,有些聪明的人已考虑到了这个潜在的问题,并且由一个lambda表达式赋值给一个std::function类型不仅仅是可能的,而且还是极其容易的:
  1. uint64_t test_accumulate_bound_lambda()  
  2. {  
  3.     uint64_t x = 0;  
  4.     std::function<void (uint64_t)> accumulator = [&x] (uint64_t i) { x += i; };  
  5.     do_test_loop(accumulator);  
  6.     return x;  
  7. }  
   通过使用 lambda语义来替代std::bind,我们获取到了std::function多态的所有威力和C++ lambda表达式所拥有的便利和高性能表现。这听起来像是一种双赢。
   对于这三个函数我们可以做个简单的比较(使用timer类):

  1. template <typename Function>  
  2. void run_test(const std::string& name, Function func)  
  3. {  
  4.     std::cout << name;  
  5.     timer t;  
  6.     volatile_write(func());  
  7.     timer::duration duration = t.elapsed();  
  8.     std::cout << '\t' << duration.count() << std::endl;  
  9. }  
  10.   
  11. int main()  
  12. {  
  13.     run_test("Accumulate (lambda)      ", &test_accumulate_lambda);  
  14.     run_test("Accumulate (bind)        ", &test_accumulate_bind);  
  15.     run_test("Accumulate (bound lambda)", &test_accumulate_bound_lambda);  
  16. }  
事不宜迟,我们先来看看使用gcc 4.4.2 -O3编译并且在Inter Core i7 Q740机器上运行的结果:
Accumulate (lambda)               7
Accumulate (bind)                    4401849
Accumulate (bound lambda)   4379315
每当我在做性能测试时看到运行结果耗非常悬殊时我都会反汇编程序看看编译器到底做了什么。
(gdb) disassemble test_accumulate_lambda
Dump of assembler code for function _Z22test_accumulate_lambdav:
   0x0000000000400e70 <+0>:     movabs $0x6f05b59b5e49b00,%rax
   0x0000000000400e75 <+5>:     retq
End of assembler dump.
在经过编译器优化之后,整个函数仅仅是将0x6f05b59b5e49b00(十进制值为:499999999500000000)移动到了rax寄存器中就返回了。编译器非常智能的知道了我们仅仅是对0到1000000000之间的数字求和并直接帮我们进行了代码替换的优化,另我影响深刻的是编译器竟然可以做到这点并且非常合理。函数的内容对do_test_loop函数的实例是静态已知,所以编译器将原有的代码转化成了如下所示的代码:

  1. uint64_t test_accumulate_lambda()  
  2. {  
  3.     uint64_t x = 0;  
  4.     // do_test_loop:  
  5.     for (uint64_t i = 0; i < 1000000000; ++i)  
  6.         x += i;  
  7.     return x;  
  8. }  
任何优秀的编译器都将对其进行优化。我认为要从这个简单例子中获取的最重要的信息是:编译器知道lambda函数是具有静态性的,因此你可以放心的使用lambda函数而不必担心它性能。那么我们调用的std::function又是怎样的一个过程呢?在这里它的多态性让我们很难去剖析,当函数do_test_loop被函数std::function<void (uint64_t)>实例化时,编译器并不知道func的行为,因此它能做任何事情(它只是std::function的入口点)。std::bind和lambda表达式之间的不同之处是极其细微的。如果你多次的运行测试用例,在我的电脑里lambda表达式的总会比std::bind的快一点,但是这些数据并不具有统计学的意义。这种性能在以后很有可能在不同的机器上会发生改变,如果我要猜测我会说这有std::reference_wrapper的作用。下面让我们来看看两个函数的堆栈。
std::bind
#0  test_accumulate_bind_function (x=@0x7fffffffe5d0, i=0) at lambda_vs_bind.cpp:106
#1  0x0000000000401111 in operator() (__args#0=0, this=<optimized out>) at /usr/local/include/gcc-4.6.2/functional:2161
#2  do_test_loop<std::function<void(long unsigned int)> > (func=<optimized out>, upper_limit=<optimized out>) at lambda_vs_bind.cpp:93
#3  test_accumulate_bind () at lambda_vs_bind.cpp:115
#4  0x0000000000401304 in run_test<unsigned long (*)()> (name=<optimized out>, func=0x401080 <test_accumulate_bind()>) at lambda_vs_bind.cpp:84
#5  0x0000000000401411 in main () at lambda_vs_bind.cpp:136

Lambda Expression
#0  std::_Function_handler<void(long unsigned int), test_accumulate_bound_lambda()::<lambda(uint64_t)> >::_M_invoke(const std::_Any_data &, unsigned long) (__functor=..., __args#0=0) at /usr/local/include/gcc-4.6.2/functional:1778
#1  0x0000000000400fa9 in operator() (__args#0=0, this=<optimized out> at /usr/local/include/gcc-4.6.2/functional:2161
#2  do_test_loop<std::function<void(long unsigned int)> > (func=<optimized out>, upper_limit=<optimized out>) at lambda_vs_bind.cpp:93
#3  test_accumulate_bound_lambda () at lambda_vs_bind.cpp:126
#4  0x0000000000401304 in run_test<unsigned long (*)()> (name=<optimized out>, func=0x400f20 <test_accumulate_bound_lambda()>) at lambda_vs_bind.cpp:84
#5  0x000000000040143e in main () at lambda_vs_bind.cpp:140
它们的不同之处仅仅是在std::function的operator()函数调用,为了正真发生了什么,我们来快速的看一下g++ 4.6.2的std::function是怎么实现的:

  1. template<typename _Res, typename... _ArgTypes>  
  2. class function<_Res(_ArgTypes...)>  
  3.     : public _Maybe_unary_or_binary_function<_Res, _ArgTypes...>,  
  4.       private _Function_base  
  5. {  
  6.     // a whole bunch of implementation details  
  7.   
  8. private:  
  9.     typedef _Res (*_Invoker_type)(const _Any_data&, _ArgTypes...);  
  10.     _Invoker_type _M_invoker;  
  11. };  
最令我感兴趣的是std::function没有使用virtual而是使用了一个函数指针。这样做有一些优势所在,这样能够让你在使用std::function时不需要处理指针和引用——这在对象内部是非常复杂的。
boost:bind
那么老方法boost::bind又是怎样的呢?为了简单起见,我们在上面的测试用例中直接用boost来替代std。
Accumulate (boost bind)                  3223174
Accumulate (boost bound lambda) 4255098
令人感到奇怪的是boost::bind要比std::bind要快25%左右,boost::bind的调用堆栈与std::bind的看起来很相像:
#0  test_accumulate_bind_function (x=@0x7fffffffe600, i=0) at lambda_vs_bind.cpp:114
#1  0x00000000004018a3 in operator() (a0=0, this=<optimized out>) at /usr/local/include/boost/function/function_template.hpp:1013
#2  do_test_loop<boost::function<void(long unsigned int)> > (upper_limit=<optimized out>, func=<optimized out>) at lambda_vs_bind.cpp:101
#3  test_accumulate_boost_bind () at lambda_vs_bind.cpp:144
#4  0x0000000000401f44 in run_test<unsigned long (*)()> (name=<optimized out>, func=0x401800 <test_accumulate_boost_bind()>) at lambda_vs_bind.cpp:92
#5  0x000000000040207e in main () at lambda_vs_bind.cpp:161
(我大概可以写一整篇的文章来描述问什么boost::bind要比std::bind快了... ...)

  1. functional  
  2. template<typename _Functor, typename... _ArgTypes>  
  3. inline  
  4. typename _Bind_helper<_Functor, _ArgTypes...>::type  
  5. bind(_Functor&& __f, _ArgTypes&&... __args)  
  6. {  
  7.     typedef _Bind_helper<_Functor, _ArgTypes...> __helper_type;  
  8.     typedef typename __helper_type::__maybe_type __maybe_type;  
  9.     typedef typename __helper_type::type __result_type;  
  10.     return __result_type(__maybe_type::__do_wrap(std::forward<_Functor>(__f)),  
  11.                         std::forward<_ArgTypes>(__args)...);  
  12. }  
  13. boost/bind/bind.hpp (with the macros expanded)  
  14. template<class F, class A1, class A2>  
  15.     _bi::bind_t<_bi::unspecified, F, typename _bi::list_av_2<A1, A2>::type>  
  16.     bind(F f, A1 a1, A2 a2)  
  17. {  
  18.     typedef typename _bi::list_av_2<A1, A2>::type list_type;  
  19.     return _bi::bind_t<_bi::unspecified, F, list_type> (f, list_type(a1, a2));  
  20. }  
更多信息

1. 源代码
你可以从这里获取到该程序的源代码http://www.gockelhut.com/c++/files/lambda_vs_bind.cpp。它在g++ 4.6.2的编译器上通过了编译并且能够运行,在支持c++11更好的编译器上编译将会更好。我的Boost库的版本是1.47,较早的版本和更新的版本的库都将工作得很好,因为boost::bind语法在一段时间内不会有太大更新(将来不一定)。如果你希望编译和运行都不用boost,那么将USE_BOOST的值改为0即可。

2. volatile_write

volatile_write函数是一个由我编写的强制的让系统在内存中写数据的简单函数,这样就能防止优化器去优化那些在函数run_test中没有做任何事情的代码。


  1. template <typename T>  
  2. void volatile_write(const T& x)  
  3. {  
  4.     volatile T* p = new T;  
  5.     *p = x;  
  6.     delete p;  
  7. }  

原文地址:http://www.gockelhut.com/c++/articles/lambda_vs_bind
lambda_vs_bind.cpp


  1. /** 
  2.  *   Copyright 2011 Travis Gockel 
  3.  * 
  4.  *  Licensed under the Apache License, Version 2.0 (the "License"); 
  5.  *  you may not use this file except in compliance with the License. 
  6.  *  You may obtain a copy of the License at 
  7.  * 
  8.  *      http://www.apache.org/licenses/LICENSE-2.0 
  9.  * 
  10.  *  Unless required by applicable law or agreed to in writing, software 
  11.  *  distributed under the License is distributed on an "AS IS" BASIS, 
  12.  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 
  13.  *  See the License for the specific language governing permissions and 
  14.  *  limitations under the License. 
  15. **/  
  16.   
  17. // Turn building and testing boost::bind on or off with this macro  
  18. #define USE_BOOST 1  
  19.   
  20. // workaround for varieties of g++-4.6 with --std=gnu++0x  
  21. #ifndef _GLIBCXX_USE_NANOSLEEP  
  22. #   define _GLIBCXX_USE_NANOSLEEP  
  23. #endif  
  24.   
  25. #include <cstdint>  
  26. #include <chrono>  
  27. #include <iostream>  
  28. #include <string>  
  29. #include <thread>  
  30.   
  31. #if USE_BOOST  
  32. #include <boost/function.hpp>  
  33. #include <boost/bind.hpp>  
  34. #endif  
  35.   
  36. class timer  
  37. {  
  38. public:  
  39.     typedef std::chrono::high_resolution_clock clock;  
  40.     typedef clock::time_point                  time_point;  
  41.     typedef clock::duration                    duration;  
  42.       
  43. public:  
  44.     timer()  
  45.     {  
  46.         reset();  
  47.     }  
  48.       
  49.     void reset()  
  50.     {  
  51.         _starttime = clock::now();  
  52.     }  
  53.   
  54.     duration elapsed() const  
  55.     {  
  56.         return clock::now() - _starttime;  
  57.     }  
  58. protected:  
  59.     time_point _starttime;  
  60. };  
  61.   
  62. bool test_timer()  
  63. {  
  64.     using std::chrono::milliseconds;  
  65.     typedef timer::duration duration;  
  66.       
  67.     const milliseconds sleep_time(500);  
  68.       
  69.     timer t;  
  70.     std::this_thread::sleep_for(sleep_time);  
  71.     duration recorded = t.elapsed();  
  72.       
  73.     // make sure the clock and this_thread::sleep_for is precise within one millisecond (or at least in agreement as to  
  74.     // how inaccurate they are)  
  75.     return (recorded - milliseconds(1) < sleep_time)  
  76.         && (recorded + milliseconds(1) > sleep_time);  
  77. }  
  78.   
  79. template <typename T>  
  80. void volatile_write(const T& x)  
  81. {  
  82.     volatile T* p = new T;  
  83.     *p = x;  
  84.     delete p;  
  85. }  
  86.   
  87. template <typename Function>  
  88. void run_test(const std::string& name, Function func)  
  89. {  
  90.     std::cout << name;  
  91.     timer t;  
  92.     volatile_write(func());  
  93.     timer::duration duration = t.elapsed();  
  94.     std::cout << '\t' << duration.count() << std::endl;  
  95. }  
  96.   
  97. template <typename Function>  
  98. void do_test_loop(Function func, const uint64_t upper_limit = 1000000000ULL)  
  99. {  
  100.     for (uint64_t i = 0; i < upper_limit; ++i)  
  101.         func(i);  
  102. }  
  103.   
  104. uint64_t test_accumulate_lambda()  
  105. {  
  106.     uint64_t x = 0;  
  107.     auto accumulator = [&x] (uint64_t i) { x += i; };  
  108.     do_test_loop(accumulator);  
  109.     return x;  
  110. }  
  111.   
  112. void test_accumulate_bind_function(uint64_t& x, uint64_t i)  
  113. {  
  114.     x += i;  
  115. }  
  116.   
  117. uint64_t test_accumulate_bind()  
  118. {  
  119.     namespace arg = std::placeholders;  
  120.       
  121.     uint64_t x = 0;  
  122.     std::function<void (uint64_t)> accumulator = std::bind(&test_accumulate_bind_function, std::ref(x), arg::_1);  
  123.     do_test_loop(accumulator);  
  124.     return x;  
  125. }  
  126.   
  127. uint64_t test_accumulate_bound_lambda()  
  128. {  
  129.     uint64_t x = 0;  
  130.     std::function<void (uint64_t)> accumulator = [&x] (uint64_t i) { x += i; };  
  131.     do_test_loop(accumulator);  
  132.     return x;  
  133. }  
  134.   
  135. #if USE_BOOST  
  136. uint64_t test_accumulate_boost_bind()  
  137. {  
  138.     uint64_t x = 0;  
  139.       
  140.     boost::function<void (uint64_t)> accumulator = boost::bind(&test_accumulate_bind_function, boost::ref(x), _1);  
  141.     do_test_loop(accumulator);  
  142.     return x;  
  143. }  
  144.   
  145. uint64_t test_accumulate_boost_bound_lambda()  
  146. {  
  147.     uint64_t x = 0;  
  148.     boost::function<void (uint64_t)> accumulator = [&x] (uint64_t i) { x += i; };  
  149.     do_test_loop(accumulator);  
  150.     return x;  
  151. }  
  152. #endif  
  153.   
  154. int main()  
  155. {  
  156.     if (!test_timer())  
  157.     {  
  158.         std::cout << "Failed timer test." << std::endl;  
  159.         return -1;  
  160.     }  
  161.       
  162.     run_test("Accumulate (lambda)            ", &test_accumulate_lambda);  
  163.     run_test("Accumulate (bind)              ", &test_accumulate_bind);  
  164.     run_test("Accumulate (bound lambda)      ", &test_accumulate_bound_lambda);  
  165.     #if USE_BOOST  
  166.     run_test("Accumulate (boost bind)        ", &test_accumulate_boost_bind);  
  167.     run_test("Accumulate (boost bound lambda)", &test_accumulate_bound_lambda);  
  168.     #endif  
  169. }  






主题推荐
lambda
c++
性能测试
namespace
源代码
猜你在找

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场


抱歉!评论已关闭.