1
      2
      3
      4
      5
      6
      7
      8
      9
     10
     11
     12
     13
     14
     15
     16
     17
     18
     19
     20
     21
     22
     23
     24
     25
     26
     27
     28
     29
     30
     31
     32
     33
     34
     35
     36
     37
     38
     39
     40
     41
     42
     43
     44
     45
     46
     47
     48
     49
     50
     51
     52
     53
     54
     55
     56
     57
     58
     59
     60
     61
     62
     63
     64
     65
     66
     67
     68
     69
     70
     71
     72
     73
     74
     75
     76
     77
     78
     79
     80
     81
     82
     83
     84
     85
     86
     87
     88
     89
     90
     91
     92
     93
     94
     95
     96
     97
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/times.h>
#include <unistd.h>

//-- timer for benchmarks ------------------------------------------------------

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
initMatrix(size_t m, size_t n,
     double *A,
     ptrdiff_t incRow, ptrdiff_t incCol)
{
    for (size_t i=0; i<m; ++i) {
        for (size_t j=0; j<n; ++j) {
            A[i*incRow+j*incCol] = i*n+j+1;
        }
    }
}

void
printMatrix(size_t m, size_t n,
            const double *A,
            ptrdiff_t incRow, ptrdiff_t incCol)
{
    for (size_t i=0; i<m; ++i) {
        for (size_t j=0; j<n; ++j) {
            printf("%10.3lf", A[i*incRow+j*incCol]);
        }
        printf("\n");
    }
    printf("\n");
}

#ifndef MAX_ROWS
#define MAX_ROWS 4500
#endif

#ifndef MAX_COLS
#define MAX_COLS 4500
#endif


int
main()
{
    double *A = (double *) malloc(MAX_ROWS*MAX_COLS*sizeof(double));

    printf("%6s %6s ", "#m", "n");
    printf("%12s ", "t (col major)");
    printf("%12s ", "t (row major)");
    printf("\n");

    for (size_t m=256, n=256; m<=MAX_ROWS && n<=MAX_COLS; m+=16, n+=16) {
        printf("%6zu %6zu ", m, n);

        size_t incRow, incCol;
        double t0, t;

        // Store A col major
        incRow = 1;
        incCol = m;
        t0 = walltime();
        initMatrix(m, n, A, incRow, incCol);
        t = walltime() - t0;

        printf("%12.2lf ", t);

        // Store A row major
        incRow = n;
        incCol = 1;
        t0 = walltime();
        initMatrix(m, n, A, incRow, incCol);
        t = walltime() - t0;
        printf("%12.2lf ", t);

        printf("\n");
    }

    free(A);

    return 0;
}