Simple Benchmark for Matrix Initialization

Content

For the benchmark we will use function walltime as a black box. As the function name suggest it simple returns the wall time.

Exercise

#include <math.h>           // for nan()
#include <stddef.h>         // for size_t, ptrdiff_t
#include <stdio.h>          // for printf
#include <stdlib.h>         // for malloc(), free()
#include <sys/times.h>      // needed for walltime()
#include <unistd.h>         // needed for walltime()

//-- Function for benchmarking and testing -------------------------------------

double
walltime()
{
   struct tms    ts;
   static double ClockTick=0.0;

   if (ClockTick==0.0) {
        ClockTick = 1.0 / ((double) sysconf(_SC_CLK_TCK));
   }
   return ((double) times(&ts)) * ClockTick;
}

//------------------------------------------------------------------------------

void
initGeMatrix(size_t m, size_t n,
             double *A,
             ptrdiff_t incRowA, ptrdiff_t incColA)
{
    for (size_t i=0; i<m; ++i) {
        for (size_t j=0; j<n; ++j) {
            A[i*incRowA + j*incColA] = i*n + j +1;
        }
    }
}

int
main()
{
    printf("#%5s %5s %10s %10s\n", "m", "n", "t (colm)", "t (rowm)");

    for (size_t m=100, n=100; m<=7000 && n<=7000; m+=100, n+=100) {

        printf(" %5ld %5ld ", (long)m, (long)n);


        // bench initialization for row major matrix
        {

            ptrdiff_t incRowA = n;
            ptrdiff_t incColA = 1;

            double *A = malloc(m*n*sizeof(double));
            if (!A) {
                abort();
            }

            double t  = walltime();
            initGeMatrix(m, n, A, incRowA, incColA);
            t = walltime() - t;

            printf("%10.2lf ", t);

            free(A);
        }

        // bench initialization for col major matrix
        {

            ptrdiff_t incRowA = 1;
            ptrdiff_t incColA = m;

            double *A = malloc(m*n*sizeof(double));
            if (!A) {
                abort();
            }

            double t  = walltime();
            initGeMatrix(m, n, A, incRowA, incColA);
            t = walltime() - t;

            printf("%10.2lf ", t);

            free(A);
        }

        printf("\n");

    }

}

Exercise