KMR
mpi_pi.reducer.c
Go to the documentation of this file.
1 /* mpi_pi.reducer.c (2014-01-10) */
2 
3 /** \file mpi_pi.reducer.c
4  \brief Example for KMRRUN. It is a reducer 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 a file which has key-values separated by lines.
33  One line is like this.
34 
35  0 7932/10000
36 
37  '0' is key and '7932/10000' is value.
38  7932 is number of points plotted in a circle and 10000 is
39  total number of points plotted.
40  By reading these numbers, it calculates pi and writes result
41  to a file. */
42 int
43 main(int argc, char *argv[])
44 {
45  char line[LINELEN];
46  int rank;
47  FILE *ifp, *ofp;
48 
49  MPI_Init(&argc, &argv);
50  MPI_Comm_rank(MPI_COMM_WORLD, &rank);
51 
52  if (argc != 2) {
53  if (rank == 0) {
54  fprintf(stderr, "specify an input file\n");
55  }
56  MPI_Abort(MPI_COMM_WORLD, 1);
57  }
58 
59  if (rank == 0) {
60  int sum_count = 0;
61  int sum_point = 0;
62  ifp = fopen(argv[1], "r");
63  while (fgets(line, sizeof(line), ifp) != NULL) {
64  char *count_s, *point_s;
65  char *cp = line;
66  int len = (int)strlen(line);
67 
68  // chomp
69  if (cp[len-1] == '\n') {
70  cp[len-1] = '\0';
71  }
72 
73  // find In count position
74  cp = strchr(line, ' ');
75  count_s = cp + 1;
76 
77  // find Total point position
78  cp = strchr(line, '/');
79  point_s = cp + 1;
80  cp[0] = '\0';
81 
82  sum_count += atoi(count_s);
83  sum_point += atoi(point_s);
84  }
85  fclose(ifp);
86 
87  double pi = 4.0 * sum_count / sum_point;
88 
89  ofp = fopen("mpi_pi.out", "w");
90  fprintf(ofp, "%f\n", pi);
91  fclose(ofp);
92  }
93 
94  MPI_Finalize();
95  return 0;
96 }
int main(int argc, char *argv[])
Main function.
#define LINELEN
Maximum length of a line of data.
Definition: kmrshell.c:25