Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include<stdio.h>
- #include<stdlib.h>
- #define SIZE 3
- int matrixA[SIZE][SIZE],matrixB[SIZE][SIZE],matrixC[SIZE][SIZE];
- __global__ void matrix_mult(int *dA,int *dB,int *dC,int dim)
- {
- // int e1,e2;
- int i=threadIdx.x;
- int j=threadIdx.y;
- int product=0,k;
- for(k=0;k<dim;k++)
- {
- product=product+dA[i*dim+k]*dB[k*dim+j];
- }
- dC[i*dim+j]=product;
- }
- void read_matrix_from_file(FILE *fp,int m,int n,int matrix[SIZE][SIZE])
- {
- int i,j;
- for(i=0;i<m;i++)
- {
- for(j=0;j<n;j++)
- {
- fscanf(fp,"%d",&matrix[i][j]);
- }
- }
- }
- void print_matrix(int matrix[SIZE][SIZE],int m,int n)
- {
- int i,j;
- for(i=0;i<n;i++)
- {
- for(j=0;j<m;j++)
- {
- printf("%d ",matrix[i][j]);
- }
- printf("\n");
- }
- }
- int main(int argc,char *argv[])
- {
- FILE *fp1=NULL,*fp2=NULL;
- int m,n,o,p,size;
- int *dA=NULL,*dB=NULL,*dC=NULL;
- enum cudaError error;
- if(argc!=7)
- {
- printf("\n(7 Parameters)./a.out matrixfile1 m n matrixfile2 o p");
- exit(0);
- }
- else
- {
- fp1=fopen(argv[1],"r+");
- fp2=fopen(argv[4],"r+");
- if(fp1==NULL||fp2==NULL)
- {
- printf("\nError in opening the file");
- exit(0);
- }
- else
- {
- m=atoi(argv[2]);
- n=atoi(argv[3]);
- o=atoi(argv[5]);
- p=atoi(argv[6]);
- size=sizeof(int)*m*m;
- // Reading the matrix from file
- read_matrix_from_file(fp1,m,n,matrixA);
- read_matrix_from_file(fp2,o,p,matrixB);
- //Print the matrix on the console
- printf("\n\nMatrixA is:\n");
- print_matrix(matrixA,m,n);
- printf("\n\nMatrixB is:\n");
- print_matrix(matrixB,o,p);
- //The first parameter of the cudaMalloc() function is the address of a pointer variable that must point to the allocated object after allocation.
- error=cudaMalloc((void**)&dA,size);
- if(error) printf("\nError in allocation");
- error=cudaMalloc((void**)&dB,size);
- if(error)printf("\nError in allocation");
- cudaMalloc((void**)&dC,size);
- if(error)printf("\nError in allocation");
- error=cudaMemcpy(dA,matrixA,size,cudaMemcpyHostToDevice);
- if(error)printf("\nError in copying data from host to device");
- error=cudaMemcpy(dB,matrixB,size,cudaMemcpyHostToDevice);
- if(error)printf("\nError in copying data from host to device");
- dim3 dimBlock(m,m);
- dim3 dimGrid(1,1);
- matrix_mult<<<dimGrid,dimBlock>>>(dA,dB,dC,m);
- error=cudaMemcpy(matrixC,dC,size,cudaMemcpyDeviceToHost);
- if(error)printf("\nError in copying data from device to host");
- cudaFree(dA);
- cudaFree(dB);
- cudaFree(dC);
- printf("\n\nThe Product matrix is:(C=A*B):\n");
- print_matrix(matrixC,m,m);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement