fork(1) download
  1.  
  2. #include <chrono>
  3. #include <cstdlib>
  4. #include <functional>
  5. #include <iostream>
  6. #include <vector>
  7.  
  8. typedef unsigned long long Integer;
  9.  
  10. struct Functor
  11. {
  12. void operator()(Integer i, Integer &sum) const
  13. {
  14. sum += std::rand();
  15. if ( i > 0 )
  16. {
  17. this->operator()(i - 1, sum);
  18. }
  19. }
  20. };
  21.  
  22. void recurse(Integer i, Integer& sum)
  23. {
  24. sum += std::rand();
  25. if ( i > 0 )
  26. {
  27. recurse(i - 1, sum);
  28. }
  29. }
  30.  
  31. int main()
  32. {
  33. const Integer n(50ull * 1000ull * 1000ull);
  34. const auto t_0(std::chrono::high_resolution_clock::now());
  35. Integer functor_sum(0);
  36. Functor functor;
  37. functor(n, functor_sum);
  38. const auto t_1(std::chrono::high_resolution_clock::now());
  39. Integer sum(0);
  40. recurse(n, sum);
  41. const auto t_2(std::chrono::high_resolution_clock::now());
  42. std::function<void(Integer, Integer&)> lambda_recurse([&lambda_recurse](Integer i, Integer& l_sum)
  43. {
  44. l_sum += std::rand();
  45. if ( i > 0 )
  46. {
  47. lambda_recurse(i - 1, l_sum);
  48. }
  49. });
  50. Integer lambda_sum(0);
  51. lambda_recurse(n, lambda_sum);
  52. const auto t_3(std::chrono::high_resolution_clock::now());
  53. std::cout << "functor: " << std::chrono::duration_cast<std::chrono::milliseconds>(t_1 - t_0).count() << "\n";
  54. std::cout << "plain: " << std::chrono::duration_cast<std::chrono::milliseconds>(t_2 - t_1).count() << "\n";
  55. std::cout << "lambda: " << std::chrono::duration_cast<std::chrono::milliseconds>(t_3 - t_2).count() << "\n";
  56. }
Success #stdin #stdout 4.18s 3032KB
stdin
Standard input is empty
stdout
functor: 1276
plain: 1233
lambda: 1674