-
Notifications
You must be signed in to change notification settings - Fork 2
/
matrixMultiplication.cpp
125 lines (102 loc) · 2.44 KB
/
matrixMultiplication.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
/*
Created by Marc Bolinches
*/
#include <iostream>
#include <string>
#include <stdlib.h>
#include <fstream>
#include <mpi.h>
#ifdef _DOUBLE_
#define Ffloat double
#else
#define Ffloat float
#endif
void copy2file(Ffloat *a, int N);
using namespace std;
int main(int narg, char **argv)
{
// initialize variables
size_t Narray = 1;
// mpi vars
int rank, worldSize;
MPI_Init(&narg, &argv);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
MPI_Comm_size(MPI_COMM_WORLD, &worldSize);
// read imput
if( narg < 2)
{
cout<< "Wrong number of arguments. Use as follows: " << endl;
cout<< " triad.p arrayLength " << endl;
cout<< "where " << std::endl;
cout << " arrayLength is the length of the array to be used" << endl;
return 1;
}else
{
Narray = stoi(argv[1]);
}
// create and allocate arrays
Ffloat **a = new Ffloat*[Narray];
Ffloat **b = new Ffloat*[Narray];
Ffloat **c = new Ffloat*[Narray];
for( size_t i = 0; i < Narray; i++)
{
a[i] = new Ffloat[Narray];
b[i] = new Ffloat[Narray];
c[i] = new Ffloat[Narray];
}
// initialize arrays (this is done in an optimal way)
for( size_t i = 0; i < Narray; i++)
for( size_t j = 0; j < Narray; j++)
{
a[i][j] = rand();
b[i][j] = rand();
c[i][j] = rand();
}
// repeat excercise "repeat" times and average times
int repeat = 20;
double avgTime = 0.;
for(int n = 0; n < repeat; n++)
{
double time = MPI_Wtime();
// operations that need to be measured
for( size_t i = 0; i < Narray; i+=4)
for(size_t j = 0; j < Narray; j++)
{
Ffloat tmp = 0.;
for(size_t ii = 0; ii < Narray; ii++)
tmp += a[i][ii]*b[ii][j];
c[i][j] = tmp;
}
avgTime += MPI_Wtime() - time;
copy2file(c[0], Narray);
// change arrays
for( size_t i = 0; i < Narray; i++)
for( size_t j = 0; j < Narray; j++)
{
a[i][j] = rand();
b[i][j] = rand();
c[i][j] = rand();
}
}
avgTime /= double(repeat);
if( rank == 0 )
cout << "GFlops/sec " << (double(Narray*Narray*Narray*Narray + Narray*Narray*Narray))/avgTime*1e-6 << endl;
for( size_t i = 0; i < Narray; i++)
delete[] a[i], b[i], c[i];
delete[] a, b, c;
MPI_Finalize();
return 0;
}
/*
Auxiliary functions
*/
void copy2file(Ffloat *a, int N)
{
ofstream file;
file.open("dummyFile.txt");
for(int i = 0; i < N; i+=10)
{
file << a[i] << endl;
}
file.close();
}