Exercise 3
Exercise 3
Source code
#include<stdio.h> #include <math.h> #include <stdlib.h> #include <omp.h> #define P 1 int main(){ int i,j,f,c,k,NR1,NR2,NC1,NC2; double **M,**A,**B,S; double inittime,endtime,tottime,inittime2,endtime2,tottime2; printf("\nChoose number scanf("%d",&NR1); printf("\nChoose number scanf("%d",&NC1); printf("\nChoose number scanf("%d",&NR2); printf("\nChoose number scanf("%d",&NC2); of rows for matrix 1: "); of columns for matrix 1: "); of rows for matrix 2: "); of columns for matrix 2: ");
if(NC1!=NR2){ printf("\nThis multiplication cant be done\n"); exit(2);} inittime2=omp_get_wtime(); omp_set_num_threads(P); /*pointers*/ if((A=(double**)calloc(NR1, sizeof(double*)))==NULL){ printf("\n\tNo memory."); exit(1); } for(i=0;i<NR1;i++){ if(((A[i]=(double*)calloc(NC1, sizeof(double)))==NULL)){ printf("\n\tNo memory."); exit(1); } } if((B=(double**)calloc(NR2, sizeof(double*)))==NULL){ printf("\n\tNo memory."); exit(1); } for(i=0;i<NR2;i++){ if(((B[i]=(double*)calloc(NC2, sizeof(double)))==NULL)){ printf("\n\tNo memory."); exit(1); } } 2
if((M=(double**)calloc(NR1, sizeof(double*)))==NULL){ printf("\n\tNo memory."); exit(1); } for(i=0;i<NR1;i++){ if(((M[i]=(double*)calloc(NC2, sizeof(double)))==NULL)){ printf("\n\tNo memory."); exit(1); } } /*matrices definition*/ for(i=0;i<NR1;i++){ for(j=0;j<NC1;j++){ A[i][j]=1.; } } for(i=0;i<NR2;i++){ for(j=0;j<NC2;j++){ B[i][j]=1.; } } /*product*/ inittime=omp_get_wtime(); #pragma omp parallel for private(c,k) for(f=0;f<NR1;f++){ for(c=0;c<NC2;c++){ for(k=0;k<NC1;k++){M[f][c]=M[f][c]+A[f][k]*B[k][c];} } } /*time*/ endtime=omp_get_wtime(); endtime2=omp_get_wtime(); tottime=endtime-inittime; tottime2=endtime2-inittime2; /*printing result*/ printf("\n\nComputation time: %lf seconds\n",tottime); printf("Total execution time: %lf seconds\n",tottime2); return(0); }