fork(1) download
  1. #include <chrono>
  2. #include <iostream>
  3. #include <numeric>
  4. #include <vector>
  5.  
  6. constexpr int square( int x )
  7. {
  8. return x * x;
  9. }
  10.  
  11. constexpr int times_two( int x )
  12. {
  13. return 2 * x;
  14. }
  15.  
  16. // map ((^2) . (^2)) $ [1,2,3]
  17. int manual_fusion( const std::vector<int>& xs )
  18. {
  19. std::vector<int> zs;
  20. zs.reserve( xs.size() );
  21. for ( int x : xs )
  22. {
  23. zs.push_back( square( times_two( x ) ) );
  24. }
  25. return zs[0];
  26. }
  27.  
  28. // map (^2) . map (^2) $ [1,2,3]
  29. int two_loops( const std::vector<int>& xs )
  30. {
  31. std::vector<int> ys;
  32. ys.reserve( xs.size() );
  33. for ( int x : xs )
  34. {
  35. ys.push_back( times_two( x ) );
  36. }
  37.  
  38. std::vector<int> zs;
  39. zs.reserve( ys.size() );
  40. for ( int y : ys )
  41. {
  42. zs.push_back( square( y ) );
  43. }
  44. return zs[0];
  45. }
  46.  
  47. // map (^2) . map (^2) $ [1,2,3]
  48. int two_loops_in_place( const std::vector<int>& xs )
  49. {
  50. std::vector<int> ys;
  51. ys.reserve( xs.size() );
  52. for ( int x : xs )
  53. {
  54. ys.push_back( times_two( x ) );
  55. }
  56.  
  57. for ( int& y : ys )
  58. {
  59. y = square( y );
  60. }
  61. return ys[0];
  62. }
  63.  
  64. template <typename F>
  65. void test( F f )
  66. {
  67. const std::vector<int> xs( 100000000, 42 );
  68.  
  69. const auto start_time = std::chrono::high_resolution_clock::now();
  70. const auto result = f( xs );
  71. const auto end_time = std::chrono::high_resolution_clock::now();
  72.  
  73. const auto elapsed = end_time - start_time;
  74. const auto elapsed_us = std::chrono::duration_cast<std::chrono::microseconds>(elapsed).count();
  75. std::cout << elapsed_us / 1000 << " ms - " << result << std::endl;
  76. }
  77.  
  78. int main()
  79. {
  80. test( manual_fusion );
  81. test( two_loops );
  82. test( two_loops_in_place );
  83. }
Success #stdin #stdout 1.64s 3472KB
stdin
Standard input is empty
stdout
311 ms - 7056
615 ms - 7056
359 ms - 7056