/
nanezz
/
thread_2
Обзор
Документация
Войти
/
nanezz
/
thread_2
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
Безопасность
master
thread2.cpp
92 строки
2 KB
nanezz
Create: thread2.cpp
02 июл 2026, 03:49
Верифицирован
02 июл 2026, 03:49
f7ba95e
Код
Авторство
О чём код?
#include <iostream> #include <vector> #include <thread> #include <chrono> #include <iomanip> #include <cstdlib> #include <numeric> #ifdef _WIN32 #include <Windows.h> #endif void sumChunk(const std::vector<int>& a, const std::vector<int>& b, std::vector<int>& c, size_t start, size_t end) { for (size_t i = start; i < end; ++i) { c[i] = a[i] + b[i]; } } double parallelSum(const std::vector<int>& a, const std::vector<int>& b, std::vector<int>& c, unsigned int numThreads) { const size_t n = a.size(); c.resize(n); auto start = std::chrono::high_resolution_clock::now(); if (numThreads > n) numThreads = static_cast<unsigned int>(n); if (numThreads == 0) numThreads = 1; std::vector<std::thread> threads; size_t chunkSize = n / numThreads; for (unsigned int t = 0; t < numThreads; ++t) { size_t begin = t * chunkSize; size_t end = (t == numThreads - 1) ? n : begin + chunkSize; threads.emplace_back(sumChunk, std::cref(a), std::cref(b), std::ref(c), begin, end); } for (auto& th : threads) { th.join(); } auto end = std::chrono::high_resolution_clock::now(); std::chrono::duration<double> elapsed = end - start; return elapsed.count(); } int main() { #ifdef _WIN32 SetConsoleCP(1251); SetConsoleOutputCP(1251); #endif unsigned int hardwareCores = std::thread::hardware_concurrency(); std::cout << "Количество аппаратных ядер: " << hardwareCores << "\n\n"; std::vector<size_t> sizes = { 1000, 10000, 100000, 1000000 }; std::vector<unsigned int> threadCounts = { 1, 2, 4, 8, 16 }; std::cout << std::left << std::setw(12) << "Потоков"; for (size_t s : sizes) { std::cout << std::setw(14) << s; } std::cout << "\n"; for (unsigned int threads : threadCounts) { std::cout << std::left << std::setw(12) << threads; for (size_t n : sizes) { std::vector<int> a(n), b(n), c; std::fill(a.begin(), a.end(), 1); std::fill(b.begin(), b.end(), 2); double time = parallelSum(a, b, c, threads); std::cout << std::setw(14) << std::fixed << std::setprecision(7) << time; } std::cout << "\n"; } return 0; }