From 3d138e5e3403b47ec5accac07c33e522a0a6a9ca Mon Sep 17 00:00:00 2001 From: Alexander Zhirov Date: Tue, 12 Oct 2021 03:40:57 +0300 Subject: [PATCH] exercise 2 --- lesson_6/Timer.hpp | 37 +++++++++++++++++ lesson_6/exercise_2.hpp | 92 +++++++++++++++++++++++++++++++++++++++++ lesson_6/main.cpp | 4 +- 3 files changed, 132 insertions(+), 1 deletion(-) create mode 100644 lesson_6/Timer.hpp create mode 100644 lesson_6/exercise_2.hpp diff --git a/lesson_6/Timer.hpp b/lesson_6/Timer.hpp new file mode 100644 index 0000000..ef85f67 --- /dev/null +++ b/lesson_6/Timer.hpp @@ -0,0 +1,37 @@ +/* + * Timer.hpp + * + * Created on: 12 окт. 2021 г. + * Author: alexander + */ + +#pragma once + +#include +#include + +class Timer +{ +private: + using clock_t = std::chrono::high_resolution_clock; + using second_t = std::chrono::duration >; + + std::string m_name; + std::chrono::time_point m_beg; + double elapsed() const + { + return std::chrono::duration_cast(clock_t::now() -m_beg).count(); + } + +public: + Timer() : m_beg(clock_t::now()) { } + Timer(std::string name) : m_name(name), m_beg(clock_t::now()) { } + + void start(std::string name) { + m_name = name; + m_beg = clock_t::now(); + } + void print() const { + std::cout << m_name << ":\t" << elapsed() * 1000 << " ms" << '\n'; + } +}; diff --git a/lesson_6/exercise_2.hpp b/lesson_6/exercise_2.hpp new file mode 100644 index 0000000..0a019ba --- /dev/null +++ b/lesson_6/exercise_2.hpp @@ -0,0 +1,92 @@ +/* + * exercise_2.hpp + * + * Created on: 11 окт. 2021 г. + * Author: alexander + */ + +#pragma once + +#include +#include +#include +#include +#include "Timer.hpp" + +bool isPrime(size_t num) +{ + size_t limit = num / 2; + + if (num > 2) + { + for (size_t i = 2; i <= limit; ++i) + { + if (num % i == 0) + { + return false; + } + } + } + + return true; +} + +void exercise_2() +{ + + size_t maxValue = 500000; + size_t counThreads = 30; + std::vector answers; + std::mutex m; + + Timer timer("With threads"); + + for (size_t i = 0; i < maxValue;) + { + std::vector v; + + for (size_t j = i + counThreads; i <= j; ++i) + { + v.push_back(std::thread([=, &m, &answers]() + { + if (isPrime(i)) + { + std::lock_guard lg(m); + answers.push_back(i); + } + })); + } + + for (auto &t : v) + { + t.join(); + } + } + +// for (const auto &a : answers) +// { +// std::cout << "Число " << a << " простое" << std::endl; +// } + + timer.print(); + + answers.clear(); + answers.shrink_to_fit(); + + timer.start("Without threads"); + + for (size_t i = 0; i < maxValue; ++i) + { + if (isPrime(i)) + { + answers.push_back(i); + } + } + +// for (const auto &a : answers) +// { +// std::cout << "Число " << a << " простое" << std::endl; +// } + + timer.print(); +} diff --git a/lesson_6/main.cpp b/lesson_6/main.cpp index f84106c..012a7bb 100644 --- a/lesson_6/main.cpp +++ b/lesson_6/main.cpp @@ -5,10 +5,12 @@ * Author: alexander */ #include "exercise_1.hpp" +#include "exercise_2.hpp" int main() { - exercise_1(); +// exercise_1(); + exercise_2(); return 0; }