-
Notifications
You must be signed in to change notification settings - Fork 0
/
pi_collective_gather.c
70 lines (55 loc) · 1.58 KB
/
pi_collective_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
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <math.h>
#include <time.h>
#include <mpi.h>
#define SEED 921
#define NUM_ITER 1000000000
int main(int argc, char* argv[])
{
int local_count = 0;
int rank, num_ranks, i, provided;
double x, y, z, pi;
MPI_Init_thread(&argc, &argv, MPI_THREAD_SINGLE, &provided);
double start_time, stop_time, elapsed_time;
start_time = MPI_Wtime();
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
MPI_Comm_size(MPI_COMM_WORLD, &num_ranks);
local_count = 0;
srand(SEED*rank); // Important: Multiply SEED by "rank" when you introduce MPI!
// Calculate PI following a Monte Carlo method
for (int iter = 0; iter < NUM_ITER/num_ranks; 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)
{
local_count++;
}
}
int counts[num_ranks];
MPI_Gather(&local_count, 1, MPI_INT, &counts, 1, MPI_INT, 0, MPI_COMM_WORLD);
if (rank == 0)
{
int global_count = 0;
for (i = 0; i < num_ranks; i++)
{
global_count += counts[i];
}
pi = ((double)global_count / (double)NUM_ITER) * 4.0;
}
stop_time = MPI_Wtime();
elapsed_time = stop_time - start_time;
if (rank == 0)
{
printf("pi: %f\n", pi);
printf("Execution_time: %f\n", elapsed_time);
}
MPI_Finalize();
return 0;
}