Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <vector>
- #include <thread>
- #include <ctime>
- #include <cstdlib>
- #include <chrono>
- std::vector<int> gen_rand_vector(const size_t &size, const int &max_value)
- {
- std::srand(std::time(NULL));
- std::vector<int> ret_value;
- for (size_t i = 0; i < size; ++i)
- ret_value.push_back(std::rand() % max_value);
- return ret_value;
- }
- long long accumulate_singlethread(const std::vector<int> &vector)
- {
- //std::cout << "Linear start\n";
- long long sum = 0;
- for (int i = 0; i < vector.size(); ++i)
- sum += vector[i];
- return sum;
- }
- long long accumulate_multithread(const std::vector<int> &vector, const int &threads_num)
- {
- //std::cout << "Linear stopped\n";
- auto accumulate_interval = [](const std::vector<int> &vector, int start, int end, long long &ans)
- {
- //std::cout << "2\n";
- register long long result = 0;
- for (int i = start; i < end; ++i)
- result += vector[i];
- ans = result;
- };
- std::vector<long long> temp_answers(threads_num);
- std::vector<std::thread> workers;
- for (int i = 0; i < threads_num; ++i)
- {
- //std::cout << "1\n";
- workers.push_back(std::thread(accumulate_interval, std::cref(vector), i * vector.size() / threads_num, (i + 1) * vector.size() / threads_num, std::ref(temp_answers[i])));
- }
- long long total_answer = 0;
- for (int i = 0; i < threads_num; ++i)
- {
- workers[i].join();
- //std::cout << "3\n";
- total_answer += temp_answers[i];
- }
- return total_answer;
- }
- int main()
- {
- std::cout << "Creating large vector...\n";
- std::vector<int> large_vector = gen_rand_vector(1e9, 1e6);
- std::cout << "Exectuting singlethread...\n";
- auto start_time = std::chrono::high_resolution_clock::now();
- long long answer_singlethread = accumulate_singlethread(large_vector);
- auto singlethread_duration = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::high_resolution_clock::now() - start_time);
- std::cout << "Executing multithread...\n";
- start_time = std::chrono::high_resolution_clock::now();
- long long answer_multithread = accumulate_multithread(large_vector, 4);
- auto multithread_duration = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::high_resolution_clock::now() - start_time);
- std::cout << "Answer for singlethread: " << answer_singlethread << std::endl <<
- "Answer for multithread: " << answer_multithread << std::endl <<
- "Singlethread duration: " << singlethread_duration.count() / 1000.0 << "s" << std::endl <<
- "Multithread duration: " << multithread_duration.count() / 1000.0 << "s" << std::endl;
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment