Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <vector>
- #include <thread>
- #include <chrono>
- class RandomCounterArray
- {
- private:
- int start;
- int end;
- std::vector<int> results;
- public:
- RandomCounterArray(int start, int end) : start(start), end(end), results(100, 0) {}
- const std::vector<int> &getResults() const
- {
- return results;
- }
- int getLength() const
- {
- int length = 0;
- for (int value : results)
- {
- length += value;
- }
- return length;
- }
- void operator()()
- {
- auto startTime = std::chrono::steady_clock::now();
- for (int i = start; i <= end; i++)
- {
- int result = randomInt();
- results[result]++;
- }
- auto endTime = std::chrono::steady_clock::now();
- std::chrono::duration<double, std::milli> duration = endTime - startTime;
- std::cout << "Thread took " << duration.count() << "ms" << std::endl;
- }
- private:
- int randomInt()
- {
- return rand() % 100;
- }
- };
- int main()
- {
- srand(time(nullptr));
- int numbers = 10000000;
- int numThreads = 1;
- int numbersPerThread = numbers / numThreads;
- std::vector<std::thread> threads;
- for (int i = 0; i < numThreads; i++)
- {
- int start = i * numbersPerThread + 1;
- int end = (i + 1) * numbersPerThread;
- threads.emplace_back(RandomCounterArray(start, end));
- }
- auto startTime = std::chrono::steady_clock::now();
- for (auto &thread : threads)
- {
- thread.join();
- }
- auto endTime = std::chrono::steady_clock::now();
- std::chrono::duration<double, std::milli> duration = endTime - startTime;
- std::cout << "Time taken: " << duration.count() << "ms" << std::endl;
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement