Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <vector>
- #include <chrono>
- #include <thread>
- using namespace std;
- using namespace std::chrono;
- class SquareCalculator
- {
- private:
- int start;
- int end;
- long long executionTime;
- vector<int> results;
- public:
- SquareCalculator(int start, int end) : start(start), end(end), executionTime(0) {}
- vector<int> getResults() const
- {
- return results;
- }
- long long getExecutionTime() const
- {
- return executionTime;
- }
- void operator()()
- {
- auto startTime = high_resolution_clock::now();
- for (int i = start; i <= end; i++)
- {
- int square = i * i;
- results.push_back(square);
- }
- auto endTime = high_resolution_clock::now();
- executionTime = duration_cast<milliseconds>(endTime - startTime).count();
- }
- };
- int main()
- {
- const int numbers = 100'000'000;
- const int numThreads = 1;
- const int numbersPerThread = numbers / numThreads;
- vector<SquareCalculator> calculators;
- for (int i = 0; i < numThreads; i++)
- {
- int start = i * numbersPerThread + 1;
- int end = (i + 1) * numbersPerThread;
- calculators.emplace_back(start, end);
- }
- auto startTime = high_resolution_clock::now();
- vector<thread> threads;
- for (auto &calculator : calculators)
- {
- threads.emplace_back(ref(calculator));
- }
- for (auto &thread : threads)
- {
- thread.join();
- }
- auto endTime = high_resolution_clock::now();
- for (size_t i = 0; i < calculators.size(); i++)
- {
- cout << "Thread " << i << " took " << calculators[i].getExecutionTime() << "ms" << endl;
- }
- cout << "Time taken: " << duration_cast<milliseconds>(endTime - startTime).count() << "ms" << endl;
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement