Advertisement
cd62131

OpenMP Matrix Multiply

Feb 4th, 2014
262
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.22 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <omp.h>
  3. #include <time.h>
  4. #include <stdlib.h>
  5. #include <string.h>
  6. #define N 723
  7. int main(void) {
  8.   int matA[N][N], matB[N][N], matC[N][N], matC_MP[N][N];
  9.   srand((unsigned int) time(NULL));
  10.   for (int i = 0; i < N; i++)
  11.     for (int j = 0; j < N; j++)
  12.       matA[i][j] = rand() % 10;
  13.   for (int i = 0; i < N; i++)
  14.     for (int j = 0; j < N; j++)
  15.       matB[i][j] = rand() % 10;
  16.  
  17.   double timer = omp_get_wtime();
  18.   for (int i = 0; i < N; i++)
  19.     for (int j = 0; j < N; j++) {
  20.       matC[i][j] = 0;
  21.       for (int k = 0; k < N; k++)
  22.         matC[i][j] += matA[i][k] * matB[k][j];
  23.     }
  24.   printf("non-omp time: %.5lf\n", omp_get_wtime() - timer);
  25.  
  26.   timer = omp_get_wtime();
  27. #pragma omp parallel num_threads(16)
  28.   {
  29. #pragma omp for ordered
  30.     for (int i = 0; i < N; i++)
  31.       for (int j = 0; j < N; j++) {
  32.         int sum = 0;
  33.         for (int k = 0; k < N; k++)
  34.           sum += matA[i][k] * matB[k][j];
  35.         matC_MP[i][j] = sum;
  36.       }
  37.   }
  38.   printf("omp time: %.5lf\n", omp_get_wtime() - timer);
  39.  
  40.   int count = 0;
  41.   for (int i = 0; i < N; i++)
  42.     for (int j = 0; j < N; j++)
  43.       if (matC[i][j] == matC_MP[i][j]) count++;
  44.   printf("Match: %d\n", count);
  45.   return 0;
  46. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement