KMR
mpi_pi.mapper.c
Go to the documentation of this file.
1 /* mpi_pi.mapper.c (2014-01-10) */
2 
3 /** \file mpi_pi.mapper.c
4  \brief Example for KMRRUN. It is a mapper for PI calculation
5  implemented using MPI.
6 
7  How to run.
8  1. create input files in a directory.
9  work/
10  000
11  001
12  002
13  ...
14 
15  Each file have one line which represents number of points to plot.
16  $ cat work/000
17  100000
18 
19  2. run by kmrrun
20  $ mpirun -np 2 ./kmrrun --mpi-proc 4 --m-mpi "./mpi_pi.mapper" \
21  -k "./mpi_pi.kvgen.sh" --r-mpi "./mpi_pi.reducer" ./work
22 */
23 
24 #include <stdio.h>
25 #include <string.h>
26 #include <stdlib.h>
27 #include <mpi.h>
28 
29 #define LINELEN 80
30 
31 /** \brief Main function.
32  Read the number of points to plot from the specified input file,
33  plot points randomly, and count the number of points plotted in
34  a circle.
35  The output is written to a file that has a line formatted in "num1/num2"
36  where num1 is number of points plotted in a circle and "num2"
37  is the total points. */
38 int
39 main(int argc, char *argv[])
40 {
41  int rank, size;
42  char line[LINELEN];
43  FILE *ifp, *ofp;
44  int points, mine, i, count, total_count;
45 
46  MPI_Init(&argc, &argv);
47  MPI_Comm_rank(MPI_COMM_WORLD, &rank);
48  MPI_Comm_size(MPI_COMM_WORLD, &size);
49  srand((unsigned int)rank);
50 
51  if (argc != 2) {
52  if (rank == 0) {
53  fprintf(stderr, "specify an input file\n");
54  }
55  MPI_Abort(MPI_COMM_WORLD, 1);
56  }
57 
58  if (rank == 0) {
59  ifp = fopen(argv[1], "r");
60  if (fgets(line, sizeof(line), ifp) == NULL) {
61  fprintf(stderr, "failed to read a file\n");
62  MPI_Abort(MPI_COMM_WORLD, 1);
63  }
64  fclose(ifp);
65  points = atoi(line);
66  }
67 
68  MPI_Bcast(&points, 1, MPI_INT, 0, MPI_COMM_WORLD);
69  mine = points / size;
70  if (rank == size - 1) {
71  mine += points % size;
72  }
73 
74  count = 0;
75  for (i = 0; i < mine; i++) {
76  float x = (float)rand() / ((float)RAND_MAX + 1.0F);
77  float y = (float)rand() / ((float)RAND_MAX + 1.0F);
78  if ( x * x + y * y < 1.0) {
79  count += 1;
80  }
81  }
82  MPI_Reduce(&count, &total_count, 1, MPI_INT, MPI_SUM, 0, MPI_COMM_WORLD);
83 
84  if (rank == 0) {
85  char *ofilename = malloc(strlen(argv[1]) + 5);
86  strncpy(ofilename, argv[1], strlen(argv[1]) + 1);
87  strncat(ofilename, ".out", 4);
88 
89  ofp = fopen(ofilename, "w");
90  fprintf(ofp, "%d/%d\n", total_count, points);
91  fclose(ofp);
92  }
93 
94  MPI_Finalize();
95  return 0;
96 }
int main(int argc, char *argv[])
Main function.
Definition: mpi_pi.mapper.c:39
#define LINELEN
Maximum length of a line of data.
Definition: kmrshell.c:25