/* =============================================================================
 * 04_locality_and_the_memory_wall.c  --  Realities #3 & #4: memory is a
 *     hierarchy, and HOW you walk it can cost 10-100x more than the "op count".
 * =============================================================================
 *
 * [Questions this demo answers]
 *   - Two loops copy the SAME data with the SAME number of operations -- why is
 *     one many times slower? (Row-major vs column-major traversal: locality.)
 *   - Summing N numbers: array vs linked list of the same N -- why can the list
 *     be ~100x slower even though both do N additions?
 *
 * [How to build & run]
 *   make  &&  ./04_locality_and_the_memory_wall
 *   cc -O2 -o 04 04_locality_and_the_memory_wall.c && ./04
 *   # Timings vary run to run and machine to machine; the RATIO is the point.
 *
 * [How to read the output]
 *   We print milliseconds for each variant and the slowdown ratio. The absolute
 *   numbers depend on your machine and its current load; the ratio (and its
 *   sign) is the robust, reproducible lesson.
 *
 * [Systems link / CS:APP 6]
 *   Main memory (DRAM) is ~100x slower than the CPU. To hide that, hardware
 *   keeps recently/nearby data in small fast CACHES, in units of ~64-128 byte
 *   "cache lines". Code with good LOCALITY -- reusing data (temporal) and
 *   touching neighbours (spatial) -- hits the cache and flies; code that jumps
 *   around misses the cache and waits on DRAM. In C, 2-D arrays are stored
 *   ROW-MAJOR: a[i][0], a[i][1], ... are adjacent. So scanning rows (inner loop
 *   over j) is cache-friendly; scanning columns (inner loop over i) touches a
 *   new line every step. This is Lecture 1's teaser for Lectures 9-10.
 * -------------------------------------------------------------------------- */

#include <stdio.h>
#include <stdlib.h>     /* malloc, free, rand, srand                           */
#include "timer.h"      /* wall_seconds()                                      */

#define N 2048          /* 2048 x 2048 ints = 16 MiB per matrix: bigger than L2 */

/* Two big matrices as file-scope arrays (so they are zero-initialized and not  */
/* on the limited stack). static = visible only in this file.                   */
static int A[N][N];
static int B[N][N];

/* ---------------------------------------------------------------------------
 * escape  --  a "do not optimize this away" barrier.
 *
 * [Idea]
 *   At -O2 the compiler can see that B is written but never read, and simply
 *   DELETE the whole copy (dead-store elimination) -- then we would time
 *   nothing (0.00 ms). This one-line inline-assembly statement does no work,
 *   but its "memory" clobber tells the compiler "memory may have been read
 *   through this pointer", so it must actually perform the stores to B. This is
 *   the standard trick for writing honest micro-benchmarks.
 * [Parameters] p -- a pointer whose target must be treated as observed.
 * [Returns] void.  [Edge cases] none; it emits no instructions.
 * [C tip] __asm__ volatile("" :: "r"(p) : "memory") = empty asm, input p in a
 *   register, clobbers "memory" so the optimizer cannot reorder/remove stores
 *   around it.
 * ------------------------------------------------------------------------- */
static inline void escape(void *p) {
    __asm__ volatile("" :: "r"(p) : "memory");
}

/* ---------------------------------------------------------------------------
 * copy_rows  --  copy A into B with the INNER loop over the column index j.
 *
 * [Idea]
 *   Fix a row i, then sweep j across that row: B[i][0], B[i][1], ... These are
 *   contiguous in memory (row-major), so each cache line brings in the next
 *   several elements for free. Good spatial locality.
 * [Parameters] none (operates on the file-scope A, B).
 * [Returns] void.
 * [Edge cases] none; both arrays are exactly N x N.
 * ------------------------------------------------------------------------- */
__attribute__((noinline))
static void copy_rows(void) {
    for (int i = 0; i < N; i++)
        for (int j = 0; j < N; j++)
            B[i][j] = A[i][j];     /* stride 1: neighbours, cache-friendly      */
}

/* ---------------------------------------------------------------------------
 * copy_cols  --  copy A into B with the INNER loop over the row index i.
 *
 * [Idea]
 *   Fix a column j, then sweep i down that column: B[0][j], B[1][j], ... These
 *   are N ints = N*4 bytes APART in memory, so almost every access lands on a
 *   different cache line. Poor spatial locality -- same ops, far more misses.
 * [Parameters] none.  [Returns] void.  [Edge cases] none.
 * ------------------------------------------------------------------------- */
__attribute__((noinline))
static void copy_cols(void) {
    for (int j = 0; j < N; j++)
        for (int i = 0; i < N; i++)
            B[i][j] = A[i][j];     /* stride N: far jumps, cache-hostile        */
}

/* A singly linked list node for the second experiment.                         */
typedef struct node { struct node *next; long v; } node;

int main(void) {
    printf("=== Demo 04: locality and the memory wall ===\n");
    printf("Matrix: %d x %d ints = %.0f MiB each (bigger than cache).\n\n",
           N, N, (double)N * N * sizeof(int) / (1024.0 * 1024.0));

    for (int i = 0; i < N; i++)      /* fill A with something                   */
        for (int j = 0; j < N; j++)
            A[i][j] = i ^ j;

    /* ---- Experiment 1: row-major vs column-major copy -------------------- */
    printf("Experiment 1: same copy, inner loop over j (rows) vs i (columns)\n");
    double best_rows = 1e30, best_cols = 1e30;
    for (int rep = 0; rep < 5; rep++) {     /* keep the best of a few reps      */
        double t0 = wall_seconds(); copy_rows(); escape(B); double t1 = wall_seconds();
        copy_cols(); escape(B); double t2 = wall_seconds();
        double r = (t1 - t0) * 1e3, c = (t2 - t1) * 1e3;   /* ms               */
        if (r < best_rows) best_rows = r;
        if (c < best_cols) best_cols = c;
    }
    printf("  rows (stride 1): %7.2f ms\n", best_rows);
    printf("  cols (stride N): %7.2f ms\n", best_cols);
    printf("  column-major is %.1fx slower -- identical ops, worse locality.\n\n",
           best_cols / best_rows);

    /* ---- Experiment 2: sum an array vs a linked list of the same N ------- */
    long n = 1L << 22;              /* ~4.2 million elements                    */
    long *arr    = malloc((size_t)n * sizeof(long));
    node *nodes  = malloc((size_t)n * sizeof(node));
    long *perm   = malloc((size_t)n * sizeof(long));
    if (!arr || !nodes || !perm) { perror("malloc"); return 1; }

    for (long i = 0; i < n; i++) { arr[i] = i; perm[i] = i; nodes[i].v = i; }

    /* Build a RANDOM permutation so the "shuffled" list hops all over memory.  */
    srand(1);                       /* fixed seed -> reproducible shuffle       */
    for (long i = n - 1; i > 0; i--) {
        long j = (((long)rand() << 16) ^ rand()) % (i + 1);
        long t = perm[i]; perm[i] = perm[j]; perm[j] = t;
    }

    printf("Experiment 2: sum %ld longs, as an array vs linked lists\n", n);

    /* array sum: contiguous, stride 1                                          */
    double t0 = wall_seconds();
    long s_arr = 0;
    for (long i = 0; i < n; i++) s_arr += arr[i];
    double t1 = wall_seconds();
    double ms_arr = (t1 - t0) * 1e3;

    /* linked list in MEMORY ORDER: node[k].next = &node[k+1]                   */
    for (long k = 0; k < n - 1; k++) nodes[k].next = &nodes[k + 1];
    nodes[n - 1].next = NULL;
    t0 = wall_seconds();
    long s_seq = 0;
    for (node *p = &nodes[0]; p; p = p->next) s_seq += p->v;
    t1 = wall_seconds();
    double ms_seq = (t1 - t0) * 1e3;

    /* linked list in RANDOM order: each next points to a random node           */
    for (long k = 0; k < n - 1; k++)
        nodes[perm[k]].next = &nodes[perm[k + 1]];
    nodes[perm[n - 1]].next = NULL;
    t0 = wall_seconds();
    long s_rnd = 0;
    for (node *p = &nodes[perm[0]]; p; p = p->next) s_rnd += p->v;
    t1 = wall_seconds();
    double ms_rnd = (t1 - t0) * 1e3;

    printf("  array           : %7.2f ms  (sum=%ld)\n", ms_arr, s_arr);
    printf("  list, in order  : %7.2f ms  (sum=%ld)\n", ms_seq, s_seq);
    printf("  list, shuffled  : %7.2f ms  (sum=%ld)\n", ms_rnd, s_rnd);
    printf("  shuffled list is %.0fx slower than the array -- same N additions,\n",
           ms_rnd / ms_arr);
    printf("  but every ->next is a cache miss into random DRAM.\n\n");

    free(arr); free(nodes); free(perm);

    printf("Observations:\n");
    printf("  * Operation count does NOT predict speed. Row vs column copy and\n");
    printf("    array vs shuffled list do the same work with wildly different\n");
    printf("    time, decided entirely by cache locality.\n");
    printf("  * C arrays are row-major: make the INNER loop stride by 1.\n");
    printf("  * Pointer-chasing data structures pay a cache miss per hop; packed\n");
    printf("    arrays win when you scan. This is why Lectures 9-10 exist.\n");
    printf("  * Absolute ms vary with machine and load; the RATIOS are the point.\n");
    return 0;
}
