1
+ #include < iostream>
2
+ #include < mpi.h>
3
+ #include < string.h>
4
+ #include < string>
5
+ #include < ctime>
6
+ #include < cstdlib>
7
+ #include < assert.h>
8
+ using namespace std ;
9
+
10
+ int converter_in_number (const string &s)
11
+ {
12
+ int len = s.length ();
13
+ int a = 0 ;
14
+ int i = 0 ;
15
+ for (i = 0 ; (i < len); i++)
16
+ a = a * 10 + (s[i] - ' 0' );
17
+ return a;
18
+ }
19
+
20
+ int main (int argc, char *argv[])
21
+ {
22
+ srand ((int )time (0 ));
23
+
24
+ string size = argv[1 ];
25
+ string l = " qwertyuiop asdfghjkl zxcvbnm" ;
26
+ int lenl = l.length ();
27
+ int len = converter_in_number (size);
28
+ len = len * 3 ;
29
+ char * s = new char [len + 1 ];
30
+ int k = 0 ;
31
+ while (k < len - 2 )
32
+ {
33
+ s[k] = ' a' ;
34
+ s[k + 1 ] = l[(int )(rand () % lenl)];
35
+ s[k + 2 ] = ' a' ;
36
+ k = k + 3 ;
37
+ }
38
+
39
+ int ProcNum, ProcRank;
40
+ double stime = 0.0 ;
41
+ double etime = 0.0 ;
42
+ double stime_ = 0.0 ;
43
+ double etime_ = 0.0 ;
44
+ int nword = 0 ;
45
+ int nword_ = 0 ;
46
+ int nresword = 0 ;
47
+ int residue = 0 ;
48
+
49
+ MPI_Init (&argc, &argv);
50
+ MPI_Comm_size (MPI_COMM_WORLD, &ProcNum);
51
+ MPI_Comm_rank (MPI_COMM_WORLD, &ProcRank);
52
+
53
+ if (ProcRank == 0 )
54
+ {
55
+
56
+ stime = MPI_Wtime ();
57
+ for (int i = 0 ; i < len; i++)
58
+ if (s[i] == ' ' )
59
+ nword++;
60
+ nword++;
61
+ etime = MPI_Wtime ();
62
+ cout << " 1 process" << endl;
63
+ cout << " Number words: " << nword << endl;
64
+ cout << " Time: " << etime - stime << " sec" << endl;
65
+ stime_ = MPI_Wtime ();
66
+ }
67
+
68
+ MPI_Bcast (s, len, MPI_CHAR, 0 , MPI_COMM_WORLD);
69
+
70
+ for (int i = len / ProcNum * ProcRank; i < len / ProcNum + len / ProcNum * ProcRank; i++)
71
+ if (s[i] == ' ' )
72
+ nword_++;
73
+
74
+ MPI_Reduce (&nword_, &nresword, 1 , MPI_INT, MPI_SUM, 0 , MPI_COMM_WORLD);
75
+
76
+ if (ProcRank == 0 )
77
+ {
78
+ residue = len % ProcNum;
79
+ if (residue)
80
+ for (int i = len - residue; i < len; i++)
81
+ if (s[i] == ' ' )
82
+ nresword++;
83
+ nresword++;
84
+ etime_ = MPI_Wtime ();
85
+ cout << ProcNum << " process" << endl;
86
+ cout << " Number words: " << nresword << endl;
87
+ cout << " Time: " << etime_ - stime_ << " sec" << endl;
88
+ }
89
+
90
+ MPI_Finalize ();
91
+ delete[] s;
92
+ return 0 ;
93
+ }
0 commit comments