-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpi_mpi.cpp
More file actions
executable file
·80 lines (64 loc) · 1.8 KB
/
Copy pathpi_mpi.cpp
File metadata and controls
executable file
·80 lines (64 loc) · 1.8 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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
#include "mpi.h"
#include <cmath>
#include <ctime>
#include <cstdlib>
#include <cstdio>
#ifndef M_PI
# define M_PI 3.14159265358979323846
#endif
#define POINTS 1000000000
int main(int argc, char *argv[]) {
int myId = 0;
int numProcs = 0;
int nameLen = 0;
char processor_name[MPI_MAX_PROCESSOR_NAME];
MPI_Init(&argc, &argv);
MPI_Comm_size(MPI_COMM_WORLD, &numProcs);
MPI_Comm_rank(MPI_COMM_WORLD, &myId);
MPI_Get_processor_name(processor_name, &nameLen);
int s = (int)floor(POINTS/numProcs);
int s0 = s + POINTS%numProcs;
double startwtime;
if (myId == 0) {
startwtime = MPI_Wtime();
}
int i = 0;
int localCount = 0;
double x = 0.0f;
double y = 0.0f;
srand(time(NULL) + (unsigned)myId);
if (myId == 0) { // Master
for (i = 0; i < s0; i++) {
x = ((double)rand()) / ((double)RAND_MAX);
y = ((double)rand()) / ((double)RAND_MAX);
if (x*x + y*y <= 1) {
localCount++;
}
}
printf("Process %d - hit %d times out of %d tries.\n", myId, localCount, s0);
} else { // Slave
for (i = 0; i < s; i++) {
x = ((double)rand()) / ((double)RAND_MAX);
y = ((double)rand()) / ((double)RAND_MAX);
if (x*x + y*y <= 1) {
localCount++;
}
}
printf("Process %d - hit %d times out of %d tries.\n", myId, localCount, s);
}
int totalSum = 0;
MPI_Reduce(&localCount, &totalSum, 1, MPI_INT, MPI_SUM, 0, MPI_COMM_WORLD);
if (myId == 0) {
double ratio = double(totalSum)/POINTS;
double pi = 4.0f * ratio;
double runTime = MPI_Wtime() - startwtime;
printf("Execution time (sec) = %f\n", runTime);
printf("Total points in circle = %d\nEstimated Pi = %.20f\n", totalSum, pi);
printf("Difference between estimated pi and M_PI = %.20f\n",
fabs(pi-M_PI));
printf("Percent error for estimated pi = %.5f%\n",
(fabs(pi-M_PI))/M_PI * 100.0);
}
MPI_Finalize();
return 0;
}