KMR
pi.reducer.c
Go to the documentation of this file.
1 /* pi.reducer.c (2014-04-04) */
2 
3 /** \file pi.reducer.c
4  \brief Example for KMRRUN. It is a reducer for PI calculation.
5 
6  How to run.
7  1. create input files in a directory.
8  work/
9  000
10  001
11  002
12  ...
13 
14  Each file have one line which represents number of points to plot.
15  $ cat work/000
16  100000
17 
18  2. run by kmrrun
19  $ mpirun -np 2 ./kmrrun -m "./pi.mapper" \
20  -k "./pi.kvgen.sh" -r "./pi.reducer" ./work
21 */
22 
23 #include <stdio.h>
24 #include <string.h>
25 #include <stdlib.h>
26 
27 #define LINELEN 80
28 
29 /** \brief Main function.
30  Read a file which has key-values separated by lines.
31  One line is like this.
32 
33  0 7932/10000
34 
35  '0' is key and '7932/10000' is value.
36  7932 is number of points plotted in a circle and 10000 is
37  total number of points plotted.
38  By reading these numbers, it calculates pi and writes result
39  to a file. */
40 int
41 main(int argc, char *argv[])
42 {
43  char line[LINELEN];
44  FILE *ifp, *ofp;
45 
46  if (argc != 2) {
47  fprintf(stderr, "specify an input file\n");
48  return 1;
49  }
50 
51  int sum_count = 0;
52  int sum_point = 0;
53  ifp = fopen(argv[1], "r");
54  while (fgets(line, sizeof(line), ifp) != NULL) {
55  char *count_s, *point_s;
56  char *cp = line;
57  int len = (int)strlen(line);
58 
59  // chomp
60  if (cp[len-1] == '\n') {
61  cp[len-1] = '\0';
62  }
63 
64  // find In count position
65  cp = strchr(line, ' ');
66  count_s = cp + 1;
67 
68  // find Total point position
69  cp = strchr(line, '/');
70  point_s = cp + 1;
71  cp[0] = '\0';
72 
73  sum_count += atoi(count_s);
74  sum_point += atoi(point_s);
75  }
76  fclose(ifp);
77 
78  double pi = 4.0 * sum_count / sum_point;
79 
80  // write result to stdout
81  printf("%f\n", pi);
82  // write result to a file
83  ofp = fopen("pi.out", "w");
84  fprintf(ofp, "%f\n", pi);
85  fclose(ofp);
86 
87  return 0;
88 }
int main(int argc, char *argv[])
Main function.
Definition: pi.reducer.c:41
#define LINELEN
Maximum length of a line of data.
Definition: kmrshell.c:25