Advertisement
Guest User

Untitled

a guest
Jul 27th, 2017
47
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.52 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. #include <random>
  4. #include <algorithm>
  5. #include <chrono>
  6.  
  7. typedef std::vector<int> Array;
  8.  
  9. typedef std::chrono::high_resolution_clock Clock;
  10. typedef Clock::rep TimeCount;
  11. typedef Clock::time_point TimePoint;
  12. typedef Clock::duration TimeDuration;
  13.  
  14. template<typename Func>
  15. TimeCount getElapsedTime(Func f) {
  16.     TimePoint start = Clock::now();
  17.     f();
  18.     TimePoint end = Clock::now();
  19.     TimeDuration elapsed = end - start;
  20.     return elapsed.count();
  21. }
  22.  
  23. template<typename Arr>
  24. void shuffleArray(Arr &chng) {
  25.     static std::random_device rng;
  26.     static std::mt19937 urng(rng());
  27.     std::shuffle(std::begin(chng), std::end(chng), urng);
  28. }
  29.  
  30. template<typename Arr>
  31. void printArray(const Arr &in) {
  32.     size_t i = 1;
  33.     std::cout << "{ ";
  34.     for (auto a: in) {
  35.         if (i > 1) {
  36.             std::cout << ", ";
  37.         }
  38.         std::cout << a;
  39.         ++i;
  40.     }
  41.     std::cout << " }" << std::endl;
  42. }
  43.  
  44. int main() {
  45.     const int N = 20;
  46.     //Array arr(N);
  47.     int arr[N];
  48.     for (int i = 1; i <= N; ++i) {
  49.         arr[i - 1] = i;
  50.     }
  51.  
  52.     std::random_device rng;
  53.     std::mt19937 urng(rng());
  54.  
  55.     shuffleArray(arr);
  56.  
  57.     printArray(arr);
  58.  
  59.     TimeCount elapsed = getElapsedTime([&]{
  60.         std::sort(std::begin(arr), std::end(arr));
  61.     });
  62.     printArray(arr);
  63.     std::cout << elapsed << std::endl;
  64.  
  65.     const int R = 1000000;
  66.     long long s = 0;
  67.     for (int i = 0; i < R; ++i) {
  68.         shuffleArray(arr);
  69.         elapsed = getElapsedTime([&]{
  70.             std::sort(std::begin(arr), std::end(arr));
  71.         });
  72.         s += elapsed;
  73.     }
  74.     s /= R;
  75.     std::cout << "Average time: " << s << std::endl;
  76. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement