Advertisement
mahmoodn

mm_omp

Mar 5th, 2022
1,165
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.23 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <time.h>
  4. #include <omp.h>
  5. #include <sys/time.h>
  6. #define N 3200
  7. void multiplyMatrices(int first[][N], int second[][N], int result[][N])
  8. {
  9.     // Multiplying first and second matrices and storing it in result
  10.     int i,j,k;
  11.         #pragma omp parallel for
  12.         for (i = 0; i < N; ++i) {
  13.           for (j = 0; j < N; ++j) {
  14.              for (k = 0; k < N; ++k) {
  15.                 result[i][j] += first[i][k] * second[k][j];
  16.              }
  17.           }
  18.         }
  19. }
  20.  
  21. void fill_matrices(int first[][N], int second[][N], int result[][N])
  22. {
  23.     srand(time(NULL)); // randomize seed
  24.     for (int i = 0; i < N; i++){
  25.         for (int j = 0; j < N; j++){
  26.             first[i][j] = rand() % 10;
  27.             second[i][j] = rand() % 10;
  28.             result[i][j] = 0;
  29.         }
  30.     }
  31. }
  32. void print(int first[][N], int second[][N], int result[][N])
  33. {
  34.     srand48(time(NULL)); // randomize seed
  35.     printf("First:\n");
  36.     for (int i = 0; i <  N; i++){
  37.         printf("[ ");
  38.         for (int j = 0; j < N; j++){
  39.             printf("%d ", first[i][j]);
  40.         }
  41.         printf("]\n");
  42.     }
  43.     printf("\nSecond:\n");
  44.     for (int i = 0; i <  N; i++){
  45.         printf("[ ");
  46.         for (int j = 0; j < N; j++){
  47.             printf("%d ", second[i][j]);
  48.         }
  49.         printf("]\n");
  50.     }
  51.     printf("\nResult:\n");
  52.     for (int i = 0; i <  N; i++){
  53.         printf("[ ");
  54.         for (int j = 0; j < N; j++){
  55.             printf("%d ", result[i][j]);
  56.         }
  57.         printf("]\n");
  58.     }  
  59. }
  60.  
  61. int main()
  62. {
  63.     double start1, start2, stop1, stop2, execution_time1, execution_time2;
  64.     omp_set_num_threads(omp_get_num_procs());
  65.     int first[N][N], second[N][N], result[N][N];
  66.  
  67.     start1 = omp_get_wtime();
  68.     fill_matrices(first, second, result);
  69.     stop1 = omp_get_wtime();
  70.  
  71.     start2 = omp_get_wtime();
  72.     multiplyMatrices(first, second, result);
  73.     stop2 = omp_get_wtime();
  74.  
  75.     execution_time1 = stop2 - start1;
  76.     execution_time2 = stop2 - start2;
  77.     //print(first, second, result);
  78.     printf("Total execution Time in seconds: %.10lf\n", execution_time1 );
  79.     printf("MM execution Time in seconds: %.10lf\n", execution_time2 );
  80.     return 0;
  81. }
  82.    
  83.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement