123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109 |
- // Compare the execution times of multiplying a matrix by a vector vs
- // a matrix by a matrix.
- //
- // Usage:
- // ./<exec name> <size of list>
-
- #include <iostream>
- #include <vector>
- #include <cstdlib>
- #include <algorithm>
-
- typedef unsigned int uint;
- using namespace std;
-
- const int SIZE = 20000;
-
- void vectorMatrixMult(const vector< vector <int> > & M, const vector<int> & y, vector<int> &res) {
- res.resize(y.size());
- for (int r = 0; r < M.size(); r++) {
- int sum = 0;
- for (int c = 0; c < y.size(); c++) {
- sum = sum + (M[r][c] * y[c]);
- }
- res[r] = sum;
- }
- }
-
- void matrixMatrixMult(const vector< vector <int> > & A,
- const vector< vector <int> > & B, vector< vector <int> > & res) {
-
- res.resize(A.size());
- for (auto &r: res) {
- r.resize(B[0].size());
- }
-
- for (uint cb = 0; cb < B[0].size(); cb++) {
- for (uint ra = 0; ra < A.size(); ra++) {
- int sum = 0;
- for (uint ca = 0; ca < A[0].size(); ca++) {
- // printf("ra ca cb: %d %d %d\n",ra,ca,cb);
- sum = sum + (A[ra][ca] * B[ca][cb]);
- }
- res[ra][cb] = sum;
- }
- }
- }
-
-
-
- void fillMatrix(vector< vector <int> > & M, uint size) {
- M.resize(size);
- for (uint r = 0; r < size; r++) {
- M[r].resize(size);
- for (uint c = 0; c < size; c++) {
- M[r][c] = rand() % size;
- }
- }
- }
-
- void fillVector(vector<int> & V, int size) {
- V.resize(size);
- for (int r = 0; r < size; r++) {
- V[r]= rand() % size;
- }
- }
-
-
- int main(int argc, char *argv[]) {
-
- if (argc < 2) {
- cout << "Usage: " << argv[0] << " <size> \n";
- exit(1);
- }
- int size = atoi(argv[1]);
-
- vector< vector<int> > M;
- vector <int> x, y;
-
- srand(time(NULL));
-
-
- fillMatrix(M,size);
- fillVector(y,size);
-
-
- double elapsed_secs;
-
- // measure vector matrix mult time
- clock_t begin = clock();
- vectorMatrixMult(M, y, x);
- clock_t end = clock();
-
- elapsed_secs = static_cast<double>(end - begin) / CLOCKS_PER_SEC;
- cout << "\nTime elapsed for vector matrix mult: " << elapsed_secs << " seconds\n";
-
- // measure matrix matrix mult time
- vector < vector <int> > R;
- begin = clock();
- matrixMatrixMult(M,M,R);
- end = clock();
-
- elapsed_secs = static_cast<double>(end - begin) / CLOCKS_PER_SEC;
- cout << "Time elapsed for matrix matrix mult: " << elapsed_secs << " seconds\n\n";
-
- return 0;
- }
-
-
|