Matrix Multiplication in C

Serial code of the matrix multiplication with dynamic memory allocation of an int variable. Apart from this, we measure execution time for a particular size. 

Program : 

#include <stdio.h>

#include <stdlib.h>

#include <time.h>


void serial_matrix_mult(int* h_a, int* h_b, int* h_result, int n);

int main()

{

    

    int n = 128;

    int* a, * b, * c;


    

  

        a = (int*)malloc(sizeof(int) * n * n);

        b = (int*)malloc(sizeof(int) * n * n);

        c = (int*)malloc(sizeof(int) * n * n);


        // initialize matrix A

        for (int i = 0; i < n; ++i) {

            for (int j = 0; j < n; ++j) {

                a[i * n + j] = 2;

                

            }

        }


        // initialize matrix B

        for (int i = 0; i < n; ++i) {

            for (int j = 0; j < n; ++j) {

                b[i * n + j] = 3;

                

            }

        }


        clock_t start, stop;


        start = clock();


        serial_matrix_mult(a, b, c, n);


        stop = clock();


        double timeTaken1 = (stop - start) / (CLOCKS_PER_SEC / (double)1000.0);

        printf("n is %d",n);

        printf(" timeTeken1: %f",timeTaken1);

      

        printf("%d \n",c[12 * n + 0] );

              

        free(a);

        free(b);

        free(c);

    

    

    return 0;

}

void serial_matrix_mult(int* h_a, int* h_b, int* h_result, int n) {

    for (int i = 0; i < n; ++i)

    {

        for (int j = 0; j < n; ++j)

        {

            int tmp = 0;

            for (int h = 0; h < n; ++h)

            {

                tmp += h_a[i * n + h] * h_b[h * n + j];

            }

            h_result[i * n + j] = tmp;

        }

    }

}



To see the profiling for this, please click here.

Comments

Post a Comment

Any Query Regarding Article Ask me in comment