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
|
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <random>
using namespace std;
int matrix_multiply(int n1, int n2, int n3, double *a, double *b, double *c);
int matrix_fill_random(int n1, int n2, double *a);
int matrix_print(int n1, int n2, double *a);
int matrix_multiply(int n1, int n2, int n3, double *a, double *b, double *c)
{
int i;
int j;
int k;
for (i=0;i<n1;i++) {
for (j=0;j<n3;j++) {
*(c+(i*n3)+j) = 0;
for (k=0;k<n2;k++) {
*(c+(i*n3)+j) += (*(a+(i*n2)+k) * (*(b+(k*n3)+j)));
}
}
}
return 0;
}
int matrix_fill_random(int n1, int n2, double *a)
{
int i;
for (i=0;i<(n1*n2);i++) {
*(a+i) = rand() % 20001 - 10000;
*(a+i) /= 10000;
}
return 0;
}
int matrix_print(int n1, int n2, double *a)
{
int i;
int j;
cout << "\n" << endl;
for (i=0;i<n1;i++) {
for (j=0;j<n2;j++) {
if (*(a+(i*n2)+j) >= 0) {
cout << " ";
}
cout << *(a+(i*n2)+j) << "\t";
}
cout << " " << endl;
}
return 0;
}
int main() {
int numRowsA;
int numColsA;
int numColsB;
int numIterations;
int i;
srand((unsigned int)time(0));
cout << "Please enter in the number of rows for Matrix A: ";
cin >> numRowsA;
cout << "Please enter in the number of columns for Matrix A: ";
cin >> numColsA;
cout << "Please enter in the number of columns for Matrix B: ";
cin >> numColsB;
cout << "Please enter in the number of iterations for repeating the multiplication: ";
cin >> numIterations;
double A[numRowsA][numColsA];
double B[numColsA][numColsB];
double C[numRowsA][numColsB];
matrix_fill_random(numRowsA,numColsA,(&A[0][0]));
matrix_fill_random(numColsA,numColsB,(&B[0][0]));
clock_t beforeMult;
clock_t afterMult;
clock_t ticks;
float seconds;
float secondsPerIteration;
beforeMult = clock();
for (i=0;i<numIterations;i++){
matrix_multiply(numRowsA,numColsA,numColsB,(&A[0][0]),(&B[0][0]),(&C[0][0]));
delete C;
}
afterMult = clock();
ticks = afterMult - beforeMult;
seconds = (float(ticks))/numIterations;
secondsPerIteration = seconds/CLOCKS_PER_SEC;
cout << "The number of total clock ticks is: " << ticks << endl;
cout << "The number of ticks per multiplication is: " << seconds << endl;
cout << "The number of seconds per multiplication is: " << secondsPerIteration << endl;
delete A;
delete B;
delete C;
}
|