-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path2.3.c
81 lines (66 loc) · 2.01 KB
/
2.3.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
#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 total_count = 0;
int flip = 1 << 24;
int rank, num_ranks, i, iter, provided;
double x, y, z, pi;
long n = NUM_ITER;
MPI_Init_thread(&argc, &argv, MPI_THREAD_SINGLE, &provided); // initialize
double start_time, stop_time, elapsed_time;
start_time = MPI_Wtime();
MPI_Comm_size(MPI_COMM_WORLD, &num_ranks); // get num of processes
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
// replace seed with 100
srand(time(NULL) + 123456789 + rank * SEED); // Important: Multiply SEED by "rank" when you introduce MPI!
flip = flip / num_ranks;
// Calculate PI following a Monte Carlo method
for (iter = 0; iter < flip; 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++;
}
}
if (rank == 0) {
int counts[num_ranks - 1];
MPI_Request requests[num_ranks - 1];
int global_count = 0;
for (i = 1; i < num_ranks; i++) {
MPI_Irecv(&counts[i-1], 1, MPI_INT, i, 0, MPI_COMM_WORLD, &requests[i-1]);
}
MPI_Waitall(num_ranks - 1, requests, MPI_STATUSES_IGNORE);
total_count += local_count;
for (i = 0; i < num_ranks - 1; i++) {
total_count += counts[i];
}
// Estimate Pi and display the result
pi = ((double)total_count / (double) (flip * num_ranks)) * 4.0;
}
else {
MPI_Send(&local_count, 1, MPI_INT, 0, 0, MPI_COMM_WORLD);
}
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);
// printf("The result is %f\n", pi);
}
MPI_Finalize();
return 0;
}