Advertisement
ahmad_zizo

openmp

Apr 30th, 2015
203
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.75 KB | None | 0 0
  1. #include <stdlib.h>
  2. #include <stdio.h>
  3. #include <errno.h>
  4. #include <pthread.h>
  5. #include <unistd.h>
  6. #include <fcntl.h>
  7. #include <string.h>
  8. #include <sys/time.h>
  9. #include <sys/wait.h>
  10. #include <sys/stat.h>
  11. #include <time.h>
  12. #include <omp.h>
  13.  
  14. double *a,*b,*c;
  15.  
  16. int M;
  17.  
  18. void print_matrix(double *m)
  19. {
  20.     int i,j;
  21.     for(i=0; i<M; i++)
  22.     {
  23.         for(j=0; j<M; j++)
  24.         {
  25.             printf("%g\t" ,*(m+M*i+j));
  26.         }
  27.         printf("\n");
  28.     }
  29.     printf("\n");
  30. }
  31.  
  32. void calc_row(int r)
  33. {
  34.     int row = r;
  35.     int j,k;
  36.  
  37.     for(j=0; j<M; j++)
  38.     {
  39.         *(c+row*M+j)=0;
  40.  
  41.         for(k=0; k<M; k++)
  42.         {
  43.             *(c+row*M+j)=*(c+row*M+j)+*(a+row*M+k)* *(b+k*M+j);
  44.         }
  45.     }
  46. }
  47.  
  48. void generate_matrix(double *A)
  49. {
  50.     int i,j;
  51.     for(i=0; i<M; i++)
  52.     {
  53.         for(j=0; j<M; j++)
  54.         {
  55.             *(A+i*M+j) = 1+rand()%100;
  56.         }
  57.     }
  58. }
  59.  
  60. int main(int argc, char *argv[])
  61. {
  62.     srand(time(NULL));
  63.     if(argc != 2)
  64.     {
  65.         printf("\nERROR\n");
  66.         exit(0);
  67.     }
  68.     if(atoi(argv[1]) < 1 )
  69.     {
  70.         printf("\nERROR\n");
  71.         exit(0);
  72.     }
  73.     clock_t t1,t2;
  74.     int i;
  75.     int args[2];
  76.     M =args[1] = atoi(argv[1]);
  77.     a = (double *)malloc(M*M*sizeof(double));
  78.     b = (double *)malloc(M*M*sizeof(double));
  79.     c = (double *)malloc(M*M*sizeof(double));
  80.  
  81.     generate_matrix(a);
  82.     generate_matrix(b);
  83.  
  84.     t1 = clock();
  85.  
  86.     #pragma omp paralell num_threads(M)
  87.     {
  88.     #pragma omp for
  89.     for(i=0 ; i< M ; i++)
  90.     {
  91.        calc_row(i);  
  92.     }
  93.     }
  94.     t2= clock();
  95.     print_matrix(a);
  96.     print_matrix(b);
  97.     print_matrix(c);
  98.  
  99.     printf("\ntime taken = %f\n\n",(double)(t2-t1)/(CLOCKS_PER_SEC / 1000.0));
  100.  
  101.     return 0;
  102. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement