KMR
pi.mapper.c
Go to the documentation of this file.
1 /* pi.mapper.c (2014-04-04) */
2 
3 /** \file pi.mapper.c
4  \brief Example for KMRRUN. It is a mapper 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 
24 #include <stdio.h>
25 #include <string.h>
26 #include <stdlib.h>
27 #include <sys/types.h>
28 #include <unistd.h>
29 
30 #define LINELEN 80
31 
32 /** \brief Main function.
33  Read the number of points to plot from the specified input file,
34  plot points randomly, and count the number of points plotted in
35  a circle.
36  The output is written to a file that has a line formatted in "num1/num2"
37  where num1 is number of points plotted in a circle and "num2"
38  is the total points. */
39 int
40 main(int argc, char *argv[])
41 {
42  char line[LINELEN];
43  FILE *ifp, *ofp;
44  int points, i, count;
45 
46  srand((unsigned int)getpid());
47 
48  if (argc != 2) {
49  fprintf(stderr, "specify an input file\n");
50  return 1;
51  }
52 
53  ifp = fopen(argv[1], "r");
54  if (fgets(line, sizeof(line), ifp) == NULL) {
55  fprintf(stderr, "failed to read the input file\n");
56  return 1;
57  }
58  fclose(ifp);
59  points = atoi(line);
60 
61  count = 0;
62  for (i = 0; i < points; i++) {
63  float x = (float)rand() / ((float)RAND_MAX + 1.0F);
64  float y = (float)rand() / ((float)RAND_MAX + 1.0F);
65  if ( x * x + y * y < 1.0) {
66  count += 1;
67  }
68  }
69 
70  char *ofilename = malloc(strlen(argv[1]) + 5);
71  strncpy(ofilename, argv[1], strlen(argv[1]) + 1);
72  strncat(ofilename, ".out", 4);
73 
74  ofp = fopen(ofilename, "w");
75  fprintf(ofp, "%d/%d\n", count, points);
76  fclose(ofp);
77 
78  return 0;
79 }
int main(int argc, char *argv[])
Main function.
Definition: pi.mapper.c:40
#define LINELEN
Maximum length of a line of data.
Definition: kmrshell.c:25