forked from caveofprogramming/Cpp-Multithreading
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path260 Timing Code.cpp
More file actions
59 lines (45 loc) · 1.17 KB
/
Copy path260 Timing Code.cpp
File metadata and controls
59 lines (45 loc) · 1.17 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
#include <iostream>
#include <future>
#include <chrono>
#include <thread>
#include <vector>
#include <mutex>
#include <cmath>
#include <iomanip>
using namespace std;
/*
* Slow Leibniz approximation.
*/
double calculate_pi(int terms, int start, int skip)
{
double sum = 0.0;
for (int i = start; i < terms; i += skip)
{
int sign = pow(-1, i);
double term = 1.0 / (i * 2 + 1);
sum += sign * term;
}
return sum * 4;
}
int main()
{
vector<shared_future<double>> futures;
const int CONCURRENCY = thread::hardware_concurrency();
auto start = chrono::steady_clock::now();
for (int i = 0; i < CONCURRENCY; i++)
{
shared_future<double> f = async(launch::async, calculate_pi, 1E8, i, CONCURRENCY);
futures.push_back(f);
}
double sum = 0.0;
for (auto f : futures)
{
sum += f.get();
}
auto end = chrono::steady_clock::now();
auto duration = chrono::duration_cast<chrono::milliseconds>(end - start).count();
cout << "Duration: " << duration << endl;
cout << setprecision(15) << "PI: " << M_PI << endl;
cout << setprecision(15) << "Sum: " << sum << endl;
return 0;
}