fork download
  1. #include <iostream>
  2.  
  3. #include <vector>
  4. #include <random>
  5. #include <chrono>
  6. #include <algorithm>
  7.  
  8. struct A {
  9. A(int i = 0) : i(i) {}
  10. int i;
  11. static int nSwaps;
  12.  
  13. friend void swap(A& l, A& r)
  14. {
  15. ++nSwaps;
  16. std::swap(l.i, r.i);
  17. }
  18.  
  19. bool operator<(const A& r) const
  20. {
  21. return i < r.i;
  22. }
  23. };
  24.  
  25. int A::nSwaps = 0;
  26.  
  27. using std::chrono::high_resolution_clock;
  28. using std::chrono::duration_cast;
  29. using std::chrono::milliseconds;
  30.  
  31.  
  32. int main()
  33. {
  34. std::vector<A> v(10000000);
  35.  
  36. std::ranlux24_base gen(std::random_device{}());
  37. std::generate(v.begin(), v.end(), [&gen]() {return gen();});
  38.  
  39. auto s = high_resolution_clock::now();
  40. std::sort(v.begin(), v.end());
  41. std::cout << duration_cast<milliseconds>(high_resolution_clock::now() - s).count()
  42. << "ms with " << A::nSwaps << " swaps\n";
  43.  
  44. A::nSwaps = 0;
  45. s = high_resolution_clock::now();
  46. std::shuffle(v.begin(), v.end(), gen);
  47. std::cout << duration_cast<milliseconds>(high_resolution_clock::now() - s).count()
  48. << "ms with " << A::nSwaps << " swaps\n";
  49. }
  50.  
Success #stdin #stdout 2.8s 3464KB
stdin
Standard input is empty
stdout
1206ms with 47566736 swaps
1386ms with 9999999 swaps