Repository navigation
Expand file tree
/
Copy pathconcurrency-example-factorize-asynchronous.cpp
More file actions
73 lines (66 loc) · 1.94 KB
/
Copy pathconcurrency-example-factorize-asynchronous.cpp
File metadata and controls
73 lines (66 loc) · 1.94 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
#include <array>
#include <chrono>
#include <future>
#include <iostream>
#include <limits>
#include <set>
#include <sstream>
#include <string>
#include <vector>
using namespace std;
struct Stopwatch {
Stopwatch(chrono::nanoseconds& result)
: result{result}, start{chrono::high_resolution_clock::now()} {}
~Stopwatch() { result = chrono::high_resolution_clock::now() - start; }
private:
chrono::nanoseconds& result;
const chrono::time_point<chrono::high_resolution_clock> start;
};
template <typename T>
std::set<T> factorize(T x) {
std::set<T> result{1};
for (T candidate{2}; candidate <= x; candidate++) {
if (x % candidate == 0) {
result.insert(candidate);
x /= candidate;
candidate = 1;
}
}
return result;
}
string factor_task(unsigned long long x) {
chrono::nanoseconds elapsed_ns;
set<unsigned long long> factors;
{
Stopwatch stopwatch{elapsed_ns};
factors = factorize(x);
}
const auto elapsed_ms =
chrono::duration_cast<chrono::milliseconds>(elapsed_ns).count();
stringstream ss;
ss << elapsed_ms << " ms: Factoring " << x << " ( ";
for (auto factor : factors) ss << factor << " ";
ss << ")\n";
return ss.str();
}
array<unsigned long long, 6> numbers{9'699'690, 179'426'549,
1'000'000'007, 4'294'967'291,
4'294'967'296, 1'309'674'368'000};
int main() {
chrono::nanoseconds elapsed_ns;
{
Stopwatch stopwatch{elapsed_ns};
vector<future<string>> factor_tasks;
for (auto number : numbers) {
factor_tasks.emplace_back(async(launch::async, factor_task, number));
// std::future task{async(launch::async, factor_task, number)} // move
// constructor...?
}
for (auto& task : factor_tasks) {
cout << task.get();
}
}
const auto elapsed_ms =
chrono::duration_cast<chrono::milliseconds>(elapsed_ns).count();
cout << elapsed_ms << "ms: total program time\n";
}