/* =============================================================================
 * 03_matmul.c  --  same multiply, six loop orders, very different speed
 * =============================================================================
 *
 * [Questions this demo answers]
 *   - Matrix multiply is O(n^3) whatever the loop order. Does the order change
 *     the running time on a real machine, and does it track the miss-rate
 *     ranking the simulator confirmed in demo 01 (kij best, jki worst)?
 *
 * [How to build & run]
 *   make && ./build/03_matmul           (native)
 *          ./build/03_matmul 512        (choose n)
 *
 * [How to read the output]
 *   One row per loop order: time, and GFLOP/s (2*n^3 / time). All six compute
 *   the identical product (checked). Times vary run to run; the RANKING and
 *   the ratio between best and worst are the stable point.
 *
 * [Systems link / CS:APP 6.6]
 *   The inner loop's stride through each matrix sets the miss rate (demo 01);
 *   the miss rate, not the operation count, sets the speed. This is the slides'
 *   "Core i7 Matrix Multiply Performance" in miniature.
 * -------------------------------------------------------------------------- */

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

static int N;
#define A(i, j) a[(i) * N + (j)]
#define B(i, j) b[(i) * N + (j)]
#define C(i, j) c[(i) * N + (j)]

/* Each variant computes C += A*B in a different nesting of i, j, k. The name is
 * the loop order from outermost to innermost. ijk/jik keep the sum in a
 * register; the others accumulate into C[i][j] in memory. */
static void mm_ijk(double *a, double *b, double *c) {
    for (int i = 0; i < N; i++)
        for (int j = 0; j < N; j++) {
            double s = 0;
            for (int k = 0; k < N; k++) s += A(i, k) * B(k, j);
            C(i, j) += s;
        }
}
static void mm_jik(double *a, double *b, double *c) {
    for (int j = 0; j < N; j++)
        for (int i = 0; i < N; i++) {
            double s = 0;
            for (int k = 0; k < N; k++) s += A(i, k) * B(k, j);
            C(i, j) += s;
        }
}
static void mm_kij(double *a, double *b, double *c) {
    for (int k = 0; k < N; k++)
        for (int i = 0; i < N; i++) {
            double r = A(i, k);
            for (int j = 0; j < N; j++) C(i, j) += r * B(k, j);
        }
}
static void mm_ikj(double *a, double *b, double *c) {
    for (int i = 0; i < N; i++)
        for (int k = 0; k < N; k++) {
            double r = A(i, k);
            for (int j = 0; j < N; j++) C(i, j) += r * B(k, j);
        }
}
static void mm_jki(double *a, double *b, double *c) {
    for (int j = 0; j < N; j++)
        for (int k = 0; k < N; k++) {
            double r = B(k, j);
            for (int i = 0; i < N; i++) C(i, j) += A(i, k) * r;
        }
}
static void mm_kji(double *a, double *b, double *c) {
    for (int k = 0; k < N; k++)
        for (int j = 0; j < N; j++) {
            double r = B(k, j);
            for (int i = 0; i < N; i++) C(i, j) += A(i, k) * r;
        }
}

struct variant { const char *name; void (*fn)(double *, double *, double *); const char *stride; };

int main(int argc, char **argv)
{
#if defined(__x86_64__)
    const char *arch = "x86-64";
#else
    const char *arch = "arm64";
#endif
    N = argc > 1 ? atoi(argv[1]) : 640;
    printf("=== Demo 03: matrix multiply, six loop orders, n = %d (%s) ===\n\n", N, arch);
    size_t bytes = (size_t)N * N * sizeof(double);
    double *a = malloc(bytes), *b = malloc(bytes), *c = malloc(bytes), *ref = malloc(bytes);
    if (!a || !b || !c || !ref) { perror("malloc"); return 1; }
    for (int i = 0; i < N * N; i++) { a[i] = (i % 7) - 3; b[i] = (i % 5) - 2; }

    struct variant vs[] = {
        {"kij", mm_kij, "inner j: B,C stride 1"},
        {"ikj", mm_ikj, "inner j: B,C stride 1"},
        {"ijk", mm_ijk, "inner k: A stride 1, B stride n"},
        {"jik", mm_jik, "inner k: A stride 1, B stride n"},
        {"jki", mm_jki, "inner i: A,C stride n"},
        {"kji", mm_kji, "inner i: A,C stride n"},
    };
    int nv = sizeof(vs) / sizeof(vs[0]);
    double times[8];
    double best = 1e18;
    for (int v = 0; v < nv; v++) {
        memset(c, 0, bytes);
        double t0 = wall_seconds();
        vs[v].fn(a, b, c);
        times[v] = wall_seconds() - t0;
        if (v == 0) memcpy(ref, c, bytes);
        else if (memcmp(ref, c, bytes) != 0) { printf("  %-5s PRODUCT MISMATCH\n", vs[v].name); times[v] = -1; }
        if (times[v] > 0 && times[v] < best) best = times[v];
    }
    printf("  %-5s %-10s %-10s %-10s %s\n", "order", "time (s)", "GFLOP/s", "vs fastest", "inner-loop stride");
    for (int v = 0; v < nv; v++) {
        if (times[v] < 0) continue;
        double gflops = 2.0 * N * N * N / times[v] / 1e9;
        printf("  %-5s %-10.3f %-10.2f %-10.1fx %s\n", vs[v].name, times[v], gflops,
               times[v] / best, vs[v].stride);
    }
    printf("\n  All six compute the identical product. kij/ikj (stride-1 inner loop)\n");
    printf("  are fastest; jki/kji (stride-n inner loop) slowest; ijk/jik between --\n");
    printf("  the ranking demo 01 predicted from miss rates, now in wall-clock time.\n\n");
    printf("Observations:\n");
    printf("  * O(n^3) operations for all; the memory access pattern sets the speed.\n");
    printf("  * A stride-1 inner loop lets each cache block serve 8 iterations; a\n"
           "    stride-n inner loop wastes most of every block.\n");
    printf("  * The compiler (-O2) vectorizes the stride-1 inner loops; it cannot do\n"
           "    much for the stride-n ones -- another reason the gap is large.\n");
    free(a); free(b); free(c); free(ref);
    return 0;
}
