fork(1) download
  1. // compile with
  2. // g++-4.8 -o main_gcc -O3 -std=c++11 -Wall -Wextra -pedantic -Werror main.cpp square.cpp
  3. // clang++ -o main_clang -O3 -std=c++11 -Wall -Wextra -pedantic -Werror main.cpp square.cpp
  4.  
  5. #include <algorithm>
  6. #include <ctime>
  7. #include <functional>
  8. #include <iostream>
  9. #include <iterator>
  10. #include <numeric>
  11. #include <string>
  12. #include <vector>
  13.  
  14. using namespace std;
  15.  
  16. typedef vector<int> Vec;
  17. //int n = 8;
  18. int n = 1000000;
  19. size_t max_print = 10;
  20. int shift = 3;
  21. int runs = 400;
  22.  
  23. void shift_rev( Vec& v, size_t a )
  24. {
  25. reverse( v.begin(), v.end() );
  26. reverse( v.begin(), v.begin() + a );
  27. reverse( v.begin() + a, v.end() );
  28. }
  29.  
  30. void shift_swap(Vec& v, size_t a)
  31. {
  32. size_t max_s = v.size() / a;
  33. for( size_t s = 1; s < max_s; ++s )
  34. for( size_t i = 0; i < a; ++i )
  35. swap( v[i], v[s*a+i] );
  36. for( size_t i = 0; i < a; ++i )
  37. swap( v[i], v[(max_s*a+i) % v.size()] );
  38. }
  39.  
  40. void print(const Vec& v)
  41. {
  42. copy( v.begin(), v.end(), ostream_iterator<int>( cout, ",") );
  43. cout << endl;
  44. }
  45.  
  46. void test( Vec v, function<void(Vec&, size_t)> f, const string& name )
  47. {
  48. unsigned int startTime = clock();
  49.  
  50. for ( int i = 0; i < runs; ++i )
  51. f( v, shift % v.size() );
  52.  
  53. // sum the result to prevent the optimizer from removing everything.
  54. auto check = accumulate( v.begin(), v.end(), 0 );
  55.  
  56. if ( v.size() <= max_print )
  57. print( v );
  58.  
  59. double duration = static_cast<double>(clock() - startTime) / CLOCKS_PER_SEC;
  60.  
  61. cout << name << " (check: " << check << "), duration: " << duration << endl;
  62. }
  63.  
  64. int main()
  65. {
  66. vector<int> v;
  67. v.reserve( n );
  68.  
  69. for (int i = 1; i <= n; ++i )
  70. v.push_back(i);
  71.  
  72. if ( v.size() <= max_print )
  73. print( v );
  74.  
  75. test( v, &shift_rev, "rev " );
  76. test( v, &shift_swap, "swap" );
  77. }
Success #stdin #stdout 2.22s 3476KB
stdin
Standard input is empty
stdout
rev  (check: 1784293664), duration: 1.24
swap (check: 1784293664), duration: 0.96