Computer Organization and Design assignements
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 

111 lines
2.7 KiB

  1. /*!
  2. \file matmul.c
  3. \brief Matrix multiplication implementation.
  4. \author Nikos Pitsianis
  5. \author Dimitris Floros
  6. \date 2020-05-05
  7. */
  8. #include <stdio.h>
  9. #include <stdlib.h>
  10. #include <math.h>
  11. #include <sys/time.h>
  12. #include <assert.h>
  13. #define MAX_ITER 10
  14. #define sub2ind(i,j,n) (j) + (i)*(n)
  15. /*
  16. * matrixMult - Matrix multiplication
  17. */
  18. void matrixMult(float * const C, /* output matrix */
  19. float const * const A, /* first matrix */
  20. float const * const B, /* second matrix */
  21. int const n) { /* number of rows/cols */
  22. for (int i = 0; i < n; i++) { /* rows */
  23. for (int j = 0; j < n; j++) { /* cols */
  24. /* initialize output value */
  25. C[ sub2ind(i,j,n) ] = 0;
  26. for (int k = 0; k < n; k++) { /* accumulate products */
  27. C[ sub2ind(i,j,n) ] +=
  28. A[ sub2ind(i,k,n) ] * B[ sub2ind(k,j,n) ];
  29. }
  30. }
  31. }
  32. } // end function 'matrixMult'
  33. /*
  34. * matrixInitAdd:
  35. * Initialize matrix with random indices and return the matrix
  36. * pointer.
  37. *
  38. */
  39. float * matrixInit(int const n) {
  40. float *M = (float *) malloc( n*n*sizeof(float) );
  41. for (int i = 0; i < n; i++) /* rows */
  42. for (int j = 0; j < n; j++) /* cols */
  43. M[ sub2ind(i,j,n) ] = (float)rand()/(float)(RAND_MAX);
  44. return M;
  45. } // end function 'matrixInitAdd'
  46. int main(int argc, char **argv)
  47. {
  48. struct timeval start, end; /* time structs */
  49. double time = 0.0; /* execution time in ms */
  50. float *A, *B, *C; /* matrix declarations */
  51. int n; /* matrix size */
  52. /* read matrix size (or use default) */
  53. if (argc != 2){
  54. fprintf( stderr, "Uasge:\n %s n\n where n is the matrix size.\n",
  55. argv[0]);
  56. exit(1);
  57. }
  58. n = atoi( argv[1] );
  59. /* initialize matrices */
  60. A = matrixInit( n );
  61. B = matrixInit( n );
  62. C = (float *) malloc( n*n*sizeof(float) );
  63. /* compute matrix multiplication */
  64. for (int it = 0; it < MAX_ITER; it++) {
  65. gettimeofday(&start, NULL);
  66. matrixMult( C, A, B, n );
  67. gettimeofday(&end, NULL);
  68. time = ( (end.tv_sec - start.tv_sec) * 1000.0 + /* sec to ms */
  69. (end.tv_usec - start.tv_usec) / 1000.0 ); /* us to ms */
  70. printf("Iter: %d Time: %f ms\n", it, time);
  71. }
  72. /* we noeed to use the result -- verify it */
  73. for (int i = 0; i < n; i++) { /* rows */
  74. for (int j = 0; j < n; j++) { /* cols */
  75. float gold = 0;
  76. for (int k = 0; k < n; k++) { /* accumulate products */
  77. gold += A[ sub2ind(i,k,n) ] * B[ sub2ind(k,j,n) ];
  78. }
  79. assert( (gold - C[sub2ind(i,j,n)]) < 1e-3 );
  80. }
  81. }
  82. }