-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathparallel_pi.cpp
More file actions
50 lines (39 loc) · 820 Bytes
/
parallel_pi.cpp
File metadata and controls
50 lines (39 loc) · 820 Bytes
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
#include <iostream>
#include <omp.h>
using namespace std;
static long num_steps = 1000000000;
double step;
int
get_num_threads_from_env ()
{
return atoi (getenv("OMP_NUM_THREADS"));
}
int
main ()
{
double pi;
double sumArray[get_num_threads_from_env ()];
double start, end;
int nthreads;
start = omp_get_wtime();
step = 1.0/static_cast<double>(num_steps);
#pragma omp parallel
{
int id = omp_get_thread_num ();
int num = omp_get_num_threads ();
double x;
sumArray[id] = 0;
if (id == 0)
nthreads = num;
for (int i = id; i < num_steps; i+=num)
{
x = (i+0.5)*step;
sumArray[id] += 4.0/(1.0+x*x);
}
}
for (int i = 0; i < nthreads; i++)
pi += sumArray[i] * step;
end = omp_get_wtime();
cout << "Result " << pi << endl;
cout << "Elapsed time " << end - start << endl;
}