#include <stdio.h>
#include <time.h>

#define N 4096
double a[N][N];

int main(void) {
    /* Fill the array before starting either timer. */
    for (int i = 0; i < N; i++) {
        for (int j = 0; j < N; j++) {
            a[i][j] = i + j;
        }
    }

    double row_sum = 0.0;
    double column_sum = 0.0;
    struct timespec start, finish;

    /* Across each row: j changes fastest. */
    clock_gettime(CLOCK_MONOTONIC, &start);
    for (int i = 0; i < N; i++) {
        for (int j = 0; j < N; j++) {
            row_sum += a[i][j];
        }
    }
    clock_gettime(CLOCK_MONOTONIC, &finish);
    double row_time = (finish.tv_sec - start.tv_sec)
                    + (finish.tv_nsec - start.tv_nsec) / 1e9;

    /* Down each column: i changes fastest. */
    clock_gettime(CLOCK_MONOTONIC, &start);
    for (int j = 0; j < N; j++) {
        for (int i = 0; i < N; i++) {
            column_sum += a[i][j];
        }
    }
    clock_gettime(CLOCK_MONOTONIC, &finish);
    double column_time = (finish.tv_sec - start.tv_sec)
                       + (finish.tv_nsec - start.tv_nsec) / 1e9;

    printf("Across rows:  %.4f seconds\n", row_time);
    printf("Down columns: %.4f seconds\n", column_time);
    printf("Row sum:      %.0f\n", row_sum);
    printf("Column sum:   %.0f\n", column_sum);
    return 0;
}
