Advertisement
TeRackSito

C++ Square Calculator

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