No Description

matrixMult.cpp 2.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. // Compare the execution times of multiplying a matrix by a vector vs
  2. // a matrix by a matrix.
  3. //
  4. // Usage:
  5. // ./<exec name> <size of list>
  6. #include <iostream>
  7. #include <vector>
  8. #include <cstdlib>
  9. #include <algorithm>
  10. typedef unsigned int uint;
  11. using namespace std;
  12. const int SIZE = 20000;
  13. void vectorMatrixMult(const vector< vector <int> > & M, const vector<int> & y, vector<int> &res) {
  14. res.resize(y.size());
  15. for (int r = 0; r < M.size(); r++) {
  16. int sum = 0;
  17. for (int c = 0; c < y.size(); c++) {
  18. sum = sum + (M[r][c] * y[c]);
  19. }
  20. res[r] = sum;
  21. }
  22. }
  23. void matrixMatrixMult(const vector< vector <int> > & A,
  24. const vector< vector <int> > & B, vector< vector <int> > & res) {
  25. res.resize(A.size());
  26. for (auto &r: res) {
  27. r.resize(B[0].size());
  28. }
  29. for (uint cb = 0; cb < B[0].size(); cb++) {
  30. for (uint ra = 0; ra < A.size(); ra++) {
  31. int sum = 0;
  32. for (uint ca = 0; ca < A[0].size(); ca++) {
  33. // printf("ra ca cb: %d %d %d\n",ra,ca,cb);
  34. sum = sum + (A[ra][ca] * B[ca][cb]);
  35. }
  36. res[ra][cb] = sum;
  37. }
  38. }
  39. }
  40. void fillMatrix(vector< vector <int> > & M, uint size) {
  41. M.resize(size);
  42. for (uint r = 0; r < size; r++) {
  43. M[r].resize(size);
  44. for (uint c = 0; c < size; c++) {
  45. M[r][c] = rand() % size;
  46. }
  47. }
  48. }
  49. void fillVector(vector<int> & V, int size) {
  50. V.resize(size);
  51. for (int r = 0; r < size; r++) {
  52. V[r]= rand() % size;
  53. }
  54. }
  55. int main(int argc, char *argv[]) {
  56. if (argc < 2) {
  57. cout << "Usage: " << argv[0] << " <size> \n";
  58. exit(1);
  59. }
  60. int size = atoi(argv[1]);
  61. vector< vector<int> > M;
  62. vector <int> x, y;
  63. srand(time(NULL));
  64. fillMatrix(M,size);
  65. fillVector(y,size);
  66. double elapsed_secs;
  67. // measure vector matrix mult time
  68. clock_t begin = clock();
  69. vectorMatrixMult(M, y, x);
  70. clock_t end = clock();
  71. elapsed_secs = static_cast<double>(end - begin) / CLOCKS_PER_SEC;
  72. cout << "\nTime elapsed for vector matrix mult: " << elapsed_secs << " seconds\n";
  73. // measure matrix matrix mult time
  74. vector < vector <int> > R;
  75. begin = clock();
  76. matrixMatrixMult(M,M,R);
  77. end = clock();
  78. elapsed_secs = static_cast<double>(end - begin) / CLOCKS_PER_SEC;
  79. cout << "Time elapsed for matrix matrix mult: " << elapsed_secs << " seconds\n\n";
  80. return 0;
  81. }