AI_UBI

C++ Test matrix mul

Apr 16th, 2016
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.56 KB | None | 0 0
  1. #include <string>
  2. #include <ppl.h>
  3. #include <chrono>
  4. #include <vector>
  5.  
  6. class Matrix
  7. {
  8.     double drand(double fMin, double fMax)
  9.     {
  10.         double f = (double)rand() / RAND_MAX;
  11.         return fMin + f * (fMax - fMin);
  12.     }
  13.  
  14. public:
  15.  
  16.     int rows = 0;
  17.     int cols = 0;
  18.  
  19.     std::vector<std::vector<double>> mat;
  20.  
  21.     Matrix(int iRows, int iCols) : rows(iRows), cols(iCols)
  22.     {
  23.         mat.resize(rows);
  24.         for (int i = 0; i < rows; i++)
  25.             mat[i].resize(cols);
  26.     }
  27.  
  28.     void RandomMatrix(double dispersion)
  29.     {
  30.         for (int i = 0; i < rows; i++)
  31.             for (int j = 0; j < cols; j++)
  32.                 mat[i][j] = drand(-dispersion, dispersion);
  33.     }
  34.  
  35.     ~Matrix()
  36.     {
  37.     }
  38.  
  39.     Matrix * operator *(const Matrix *m) const
  40.     {
  41.         Matrix *rs = new Matrix(cols, m->rows);
  42.  
  43.         concurrency::parallel_for(size_t(0), size_t(rs->rows), [&](size_t i)
  44.         {
  45.             for (int k = 0; k < this->cols; k++)
  46.             {
  47.                 for (int j = 0; j < rs->cols; j++)
  48.                     rs->mat[i][j] += mat[i][k] * m->mat[k][j];
  49.             }
  50.         });
  51.  
  52.         return rs;
  53.     }
  54. };
  55. typedef std::chrono::high_resolution_clock Clock;
  56.  
  57. int main()
  58. {
  59.     const int TRIALS = 10;
  60.  
  61.     Matrix A(2000, 2000);
  62.     Matrix B(2000, 2000);
  63.  
  64.     A.RandomMatrix(1.0);
  65.     B.RandomMatrix(1.0);
  66.  
  67.     std::vector<Matrix *> mList;
  68.  
  69.     printf("Starting trials!\n");
  70.  
  71.     //actual trials
  72.     std::chrono::time_point<std::chrono::steady_clock> before, after;
  73.  
  74.     before = Clock::now();
  75.    
  76.     for (int i = 0; i < TRIALS; i++)
  77.     {
  78.         mList.push_back(A * &B);
  79.     }
  80.  
  81.     after = Clock::now();
  82.  
  83.     std::chrono::duration<double, std::milli> fp_ms = after - before;
  84.  
  85.     printf("Milliseconds: %f\n", fp_ms);
  86.     getchar();
  87.  
  88.     return 0;
  89. }
Add Comment
Please, Sign In to add comment