exercise 2

This commit is contained in:
Alexander Zhirov 2021-10-12 03:40:57 +03:00
parent 100e897201
commit 3d138e5e34
3 changed files with 132 additions and 1 deletions

37
lesson_6/Timer.hpp Normal file
View File

@ -0,0 +1,37 @@
/*
* Timer.hpp
*
* Created on: 12 окт. 2021 г.
* Author: alexander
*/
#pragma once
#include <iostream>
#include <chrono>
class Timer
{
private:
using clock_t = std::chrono::high_resolution_clock;
using second_t = std::chrono::duration<double, std::ratio<1> >;
std::string m_name;
std::chrono::time_point<clock_t> m_beg;
double elapsed() const
{
return std::chrono::duration_cast<second_t>(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';
}
};

92
lesson_6/exercise_2.hpp Normal file
View File

@ -0,0 +1,92 @@
/*
* exercise_2.hpp
*
* Created on: 11 окт. 2021 г.
* Author: alexander
*/
#pragma once
#include <iostream>
#include <thread>
#include <vector>
#include <mutex>
#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<size_t> answers;
std::mutex m;
Timer timer("With threads");
for (size_t i = 0; i < maxValue;)
{
std::vector<std::thread> 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();
}

View File

@ -5,10 +5,12 @@
* Author: alexander
*/
#include "exercise_1.hpp"
#include "exercise_2.hpp"
int main()
{
exercise_1();
// exercise_1();
exercise_2();
return 0;
}