/* =============================================================================
 * 01_locality.c  --  spatial locality you can feel: row-major vs column-major
 * =============================================================================
 *
 * [Questions this demo answers]
 *   - The slides claim you can look at a loop and judge its locality. Two loops
 *     sum the same matrix in a different order -- does the order matter, and by
 *     how much on this machine?
 *   - Why does scanning a C array in ROW order beat COLUMN order, given that
 *     both touch exactly the same elements the same number of times?
 *   - Can a bad 3-D traversal be fixed by permuting the loops?
 *
 * [How to build & run]
 *   make && ./build/01_locality            (native)
 *          ./build/01_locality_x86         (x86-64 under Rosetta 2, if built)
 *
 * [How to read the output]
 *   Each test reports time per element and an effective read throughput. The
 *   times vary run to run (it is a measurement), so one run is shown and the
 *   RATIO between orders -- which is stable -- is the point.
 *
 * [Systems link / CS:APP 6.2]
 *   A C array is row-major (Lecture 5): a[i][j] and a[i][j+1] are adjacent in
 *   memory, a[i][j] and a[i+1][j] are N elements apart. The cache moves data in
 *   64-byte blocks, so a stride-1 scan reuses each block 8-16 times (spatial
 *   locality) while a stride-N scan may touch a fresh block every element.
 * -------------------------------------------------------------------------- */

#include <stdio.h>
#include <stdlib.h>
#include "timer.h"

#define N 4096                      /* an N x N matrix of int: 64 MiB, >> any cache */

static int (*A)[N];                 /* pointer to rows of N ints (heap-allocated)  */

/* [Idea] Sum in ROW order: j is the inner loop, so successive accesses are
 *   a[i][0], a[i][1], ... -- stride 1, adjacent in memory. Good spatial locality. */
static long sum_rows(void)
{
    long sum = 0;
    for (int i = 0; i < N; i++)
        for (int j = 0; j < N; j++)
            sum += A[i][j];
    return sum;
}

/* [Idea] Sum in COLUMN order: i is the inner loop, so successive accesses are
 *   a[0][j], a[1][j], ... -- stride N (N*4 = 16384 bytes apart). Each touches a
 *   different cache block; poor spatial locality. Same elements, same count. */
static long sum_cols(void)
{
    long sum = 0;
    for (int j = 0; j < N; j++)
        for (int i = 0; i < N; i++)
            sum += A[i][j];
    return sum;
}

/* [Idea] time a function over the whole matrix; [Returns] seconds. */
static double time_it(long (*f)(void), long *out)
{
    double t0 = wall_seconds();
    *out = f();
    return wall_seconds() - t0;
}

static void report(const char *label, double secs, const char *loc)
{
    double per = secs / ((double)N * N) * 1e9;              /* ns per element */
    double gbs = (double)N * N * sizeof(int) / secs / 1e9;  /* GB/s read */
    printf("  %-26s %7.3f s   %6.2f ns/elem   %6.2f GB/s   (%s locality)\n",
           label, secs, per, gbs, loc);
}

int main(void)
{
#if defined(__x86_64__)
    const char *arch = "x86-64";
#else
    const char *arch = "arm64";
#endif
    printf("=== Demo 01: spatial locality, row-major vs column-major (%s) ===\n\n", arch);
    A = malloc(sizeof(int) * N * N);
    if (!A) { perror("malloc"); return 1; }
    for (int i = 0; i < N; i++)
        for (int j = 0; j < N; j++)
            A[i][j] = (i * 7 + j) & 0x3F;

    long s1, s2;
    double warm = time_it(sum_rows, &s1);     /* warm the TLB/page tables once */
    (void)warm;
    double tr = time_it(sum_rows, &s1);
    double tc = time_it(sum_cols, &s2);
    printf("  matrix: %d x %d ints = %.0f MiB (far larger than any cache)\n\n",
           N, N, (double)N * N * sizeof(int) / (1 << 20));
    report("row order (stride 1)", tr, "good");
    report("column order (stride N)", tc, "poor");
    printf("\n  same sum (%ld == %ld): %s\n", s1, s2, s1 == s2 ? "yes" : "NO");
    printf("  column order was %.1fx SLOWER, though it does identical arithmetic.\n", tc / tr);
    printf("  The only difference is the memory access pattern: stride 1 reuses each\n");
    printf("  64-byte cache block for %zu ints; stride N touches a new block each time.\n\n",
           (size_t)(64 / sizeof(int)));

    printf("Observations:\n");
    printf("  * Locality is a property of the ACCESS ORDER, not the computation. Both\n"
           "    loops read every element once and add it; only the order differs.\n");
    printf("  * Row-major C arrays reward a stride-1 (row) inner loop. Reach for the\n"
           "    innermost index that varies the LAST array subscript.\n");
    printf("  * The slides' 3-D example sum_array_3d is fixed the same way: make the\n"
           "    loop over the LAST subscript the innermost one, so the scan is stride 1.\n");
    free(A);
    return 0;
}
