fork 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. template <typename F>
  48. void test( F f )
  49. {
  50. const std::vector<int> xs( 100000000, 42 );
  51.  
  52. const auto start_time = std::chrono::high_resolution_clock::now();
  53. const auto result = f( xs );
  54. const auto end_time = std::chrono::high_resolution_clock::now();
  55.  
  56. const auto elapsed = end_time - start_time;
  57. const auto elapsed_us = std::chrono::duration_cast<std::chrono::microseconds>(elapsed).count();
  58. std::cout << elapsed_us / 1000 << " ms - " << result << std::endl;
  59. }
  60.  
  61. int main()
  62. {
  63. test( manual_fusion );
  64. test( two_loops );
  65. }
Success #stdin #stdout 1.14s 3472KB
stdin
Standard input is empty
stdout
306 ms - 7056
607 ms - 7056