-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpi_mpi_gather.c
83 lines (61 loc) · 1.76 KB
/
pi_mpi_gather.c
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
74
75
76
77
78
79
80
81
82
83
#include <mpi.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <math.h>
#include <time.h>
#define SEED 921
#define NUM_ITER 1000000000
int main(int argc, char *argv[]){
int rank, size, provided;
double tstart, tstop, pi;
int root = 0;
//initialize mpi
MPI_Init_thread(&argc, &argv, MPI_THREAD_SINGLE, &provided);
tstart = MPI_Wtime();
//get total processes
MPI_Comm_size(MPI_COMM_WORLD, &size);
//get process rank
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
srand(rank * SEED);
int count= 0; int total_count = 0;
int send_buffer[size];
int receive_buffer[size];
for(int i = 0; i < size; i++){
send_buffer[i] = 0;
receive_buffer[i] = 0;
}
double x, y, z;
int proc_iter = ceil((NUM_ITER/size));
// Calculate PI following a Monte Carlo method
for (int iter = 0; iter < proc_iter; iter++)
{
// Generate random (X,Y) points
x = (double)random() / (double)RAND_MAX;
y = (double)random() / (double)RAND_MAX;
z = sqrt((x*x) + (y*y));
// Check if point is in unit circle
if (z <= 1.0)
{
count++;
}
}
send_buffer[0] = count;
int root = 0;
MPI_Gather(send_buffer,1,MPI_INT,receive_buffer,1,MPI_INT,root,MPI_COMM_WORLD);
if(rank == root){
total_count = count;
for(int i = 1; i < size; i++){
total_count += receive_buffer[i];
}
pi = ((double)total_count / (double)(proc_iter * size)) * 4.0;
}
tstop = MPI_Wtime();
if(rank == root){
printf("The result of pi is %f\n", pi);
printf("Total elapsed time is %f\n", (tstop -tstart));
}
MPI_Finalize();
return 0;
}