Advertisement
TeRackSito

C++ Random Integer 0-99 Array optimization

Apr 21st, 2024
562
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.81 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. #include <thread>
  4. #include <chrono>
  5.  
  6. class RandomCounterArray
  7. {
  8. private:
  9.     int start;
  10.     int end;
  11.     std::vector<int> results;
  12.  
  13. public:
  14.     RandomCounterArray(int start, int end) : start(start), end(end), results(100, 0) {}
  15.  
  16.     const std::vector<int> &getResults() const
  17.     {
  18.         return results;
  19.     }
  20.  
  21.     int getLength() const
  22.     {
  23.         int length = 0;
  24.         for (int value : results)
  25.         {
  26.             length += value;
  27.         }
  28.         return length;
  29.     }
  30.  
  31.     void operator()()
  32.     {
  33.         auto startTime = std::chrono::steady_clock::now();
  34.         for (int i = start; i <= end; i++)
  35.         {
  36.             int result = randomInt();
  37.             results[result]++;
  38.         }
  39.         auto endTime = std::chrono::steady_clock::now();
  40.         std::chrono::duration<double, std::milli> duration = endTime - startTime;
  41.         std::cout << "Thread took " << duration.count() << "ms" << std::endl;
  42.     }
  43.  
  44. private:
  45.     int randomInt()
  46.     {
  47.         return rand() % 100;
  48.     }
  49. };
  50.  
  51. int main()
  52. {
  53.     srand(time(nullptr));
  54.  
  55.     int numbers = 10000000;
  56.     int numThreads = 1;
  57.     int numbersPerThread = numbers / numThreads;
  58.     std::vector<std::thread> threads;
  59.  
  60.     for (int i = 0; i < numThreads; i++)
  61.     {
  62.         int start = i * numbersPerThread + 1;
  63.         int end = (i + 1) * numbersPerThread;
  64.         threads.emplace_back(RandomCounterArray(start, end));
  65.     }
  66.  
  67.     auto startTime = std::chrono::steady_clock::now();
  68.  
  69.     for (auto &thread : threads)
  70.     {
  71.         thread.join();
  72.     }
  73.  
  74.     auto endTime = std::chrono::steady_clock::now();
  75.     std::chrono::duration<double, std::milli> duration = endTime - startTime;
  76.  
  77.     std::cout << "Time taken: " << duration.count() << "ms" << std::endl;
  78.  
  79.     return 0;
  80. }
  81.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement