/* Written by Holguer A Becerra UBC Student Master of Biomedical Engineering Course: ECE 328 Prof. Guy Lemiuex. Year 2015-Winter Term 1 */ #include #include #include #include #define INT 0 #define FLOAT 1 #define DOUBLE 1 #define TYPE_VAR INT #if TYPE_VAR == INT int * matrix1; int * matrix2; int * matrix3; int sum; #elif TYPE_VAR == FLOAT float * matrix1; float * matrix2; float * matrix3; float sum; #elif TYPE_VAR == DOUBLE double * matrix1; double * matrix2; double * matrix3; double sum; #endif double PCFreq = 0.0; __int64 CounterStart = 0; double performance_counter=0.0; void StartCounter(); double GetCounter(); int main(int argc, char *argv[]) { int N,rows,columns; int c,d,k; if(argc<=1){ printf("too few arguments"); return 0; } // the first argument has the number of rows, in this case the number of columns are the same as the number of rows. sscanf(argv[1],"%d",&N); /* initialize random seed: */ srand (time(NULL)); StartCounter(); // Initialize Matrices #if TYPE_VAR == INT matrix1=(int *)malloc(N*N*sizeof(int)); matrix2=(int *)malloc(N*N*sizeof(int)); matrix3=(int *)malloc(N*N*sizeof(int)); #elif TYPE_VAR == FLOAT matrix1=(float *)malloc(N*N*sizeof(float)); matrix2=(float *)malloc(N*N*sizeof(float)); matrix3=(float *)malloc(N*N*sizeof(float)); #elif TYPE_VAR == DOUBLE matrix1=(double *)malloc(N*N*sizeof(double)); matrix2=(double *)malloc(N*N*sizeof(double)); matrix3=(double *)malloc(N*N*sizeof(double)); #endif printf("Initializing matrices\n"); for (rows= 0; rows < N*N; rows++){ #if TYPE_VAR == INT *(matrix1+rows)=rand() % 1000 + 1; *(matrix2+rows)=rand() % 1000 + 7; //printf("1[%d,%d]=%d\n",rows/N,rows,*(matrix1+rows)); //printf("2[%d,%d]=%d\n",rows/N,rows,*(matrix2+rows)); #elif TYPE_VAR == FLOAT *(matrix1+rows)=rand() % 1000 + 1.5; *(matrix2+rows)=rand() % 1000 + 7.07; //printf("1[%d,%d]=%f\n",rows/N,rows,*(matrix1+rows)); //printf("2[%d,%d]=%f\n",rows/N,rows,*(matrix2+rows)); #elif TYPE_VAR == DOUBLE *(matrix1+rows)=rand() % 1000 + 1.5; *(matrix2+rows)=rand() % 1000 + 7.07; //printf("1[%d,%d]=%f\n",rows/N,rows,*(matrix1+rows)); //printf("2[%d,%d]=%f\n",rows/N,rows,*(matrix2+rows)); #endif } // Performance Start StartCounter(); // Improved int ho=0; for (c = 0; c < N; c++) { ho=c*N; for (k = 0; k < N; k++) { for (d = 0; d < N; d++) { *(matrix3+ho+d) += (*(matrix1+ho+k))*(*(matrix2+k*N+d)); //printf("C(%d,%d)=A(%d,%d)*B(%d,%d);\n",ho,d,ho,k,k*N,d); } } } // Performance Finish and Measure performance_counter=GetCounter(); printf("\n Improved Mutiplication time: %f ms\n",performance_counter); // free memory free(matrix1); free(matrix2); return 0; } void StartCounter() { LARGE_INTEGER li; if(!QueryPerformanceFrequency(&li)) { printf("QueryPerformanceFrequency failed!\n"); } PCFreq = (double)li.QuadPart/1000.0; QueryPerformanceCounter(&li); CounterStart = li.QuadPart; } double GetCounter() { LARGE_INTEGER li; QueryPerformanceCounter(&li); return (double)(li.QuadPart-CounterStart)/PCFreq; }