/* =============================================================================
 * 01_parallel_sum.c -- speedup, and what actually limits it
 * =============================================================================
 *
 * [Idea]
 *   Reducing an array is "embarrassingly parallel": split it into T pieces, let
 *   T threads work, combine. No dependencies, no communication. So it should
 *   scale perfectly to T cores. It does not, and WHY it does not is the lesson.
 *
 *   The point of this demo is that the answer depends on which resource runs
 *   out first, so it measures TWO workloads with the same structure:
 *
 *     A. MEMORY-BOUND: sum a 512 MB array. Each core does almost no arithmetic
 *        and streams a lot of data, so the limit is MEMORY BANDWIDTH, which is
 *        shared by all cores. Expect the curve to flatten very early.
 *
 *     B. COMPUTE-BOUND: a transcendental-ish reduction over a 1 MB array that
 *        fits in cache, repeated. Each core works out of its own cache, so the
 *        limit is CORES. Expect scaling up to the performance-core count, then
 *        a knee.
 *
 *   It also shows, briefly, why per-element synchronization is never the answer.
 *
 * [Benchmarking discipline -- this demo was wrong once]
 *   The first version of this file measured 1 thread first and reported a 9.78x
 *   speedup on 2 threads (489% "efficiency"), which is impossible. The cause
 *   was a WARM-UP artefact: the first pass over a freshly written 512 MB array
 *   costs ~44 ms (page mappings, TLB, dirty write-back) while later passes cost
 *   ~6 ms. So the 1-thread baseline was cold and everything else was warm.
 *   Two fixes, both standard and both applied here:
 *     - a WARM-UP pass before any timing;
 *     - REPS repetitions per thread count, reporting the BEST (minimum) time.
 *   Benchmarking a warm system against a cold baseline is the easiest way to
 *   measure a speedup that does not exist.
 *
 * [This machine]
 *   Apple M4 Pro: 12 cores, but 8 PERFORMANCE + 4 EFFICIENCY (see demo 04).
 *   Perfect 12x is impossible in principle -- the last 4 cores are slower.
 *
 * Build & run:    make run
 * -----------------------------------------------------------------------------
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <pthread.h>
#include <stdatomic.h>
#include <sys/time.h>

#define MAXTHREADS 12
#define REPS       3                        /* timed repetitions; best wins */

#define N_MEM      (64L * 1024 * 1024)      /* 512 MB of long: memory-bound  */
#define N_CPU      (128L * 1024)            /* 1 MB of long: fits in cache   */
#define CPU_ROUNDS 64                        /* repeat the compute workload   */

static long *mem_array;
static long *cpu_array;

/* Per-thread results, padded to this machine's 128-byte cache line so threads
 * never write the same line. Demo 02 measures what happens without this. */
typedef struct { double value; char pad[128 - sizeof(double)]; } padded_t;
static padded_t partial[MAXTHREADS];

typedef struct { int id; long start, end; } range_t;
static range_t range[MAXTHREADS];

static double now_ms(void)
{
    struct timeval tv;
    gettimeofday(&tv, NULL);
    return tv.tv_sec * 1000.0 + tv.tv_usec / 1000.0;
}

/* ---- workload A: a plain sum. Almost no arithmetic per byte read. -------- */
static void *work_memory(void *vargp)
{
    range_t *r = vargp;
    long local = 0;
    for (long i = r->start; i < r->end; i++)
        local += mem_array[i];
    partial[r->id].value = (double)local;
    return NULL;
}

/* ---- workload B: real arithmetic per element, over a cache-resident array. */
static void *work_compute(void *vargp)
{
    range_t *r = vargp;
    double local = 0;
    for (int round = 0; round < CPU_ROUNDS; round++)
        for (long i = r->start; i < r->end; i++) {
            /* Enough floating-point work that the core, not the memory
               system, is the bottleneck. */
            double x = (double)cpu_array[i];
            local += sqrt(x) * 1.000001 + x * 0.5;
        }
    partial[r->id].value = local;
    return NULL;
}

/* Run `fn` with `nthreads` threads over [0, n); return elapsed ms. */
static double once(void *(*fn)(void *), int nthreads, long n, double *total_out)
{
    pthread_t tid[MAXTHREADS];
    memset(partial, 0, sizeof(partial));

    long chunk = n / nthreads;
    for (int i = 0; i < nthreads; i++) {
        range[i].id    = i;
        range[i].start = i * chunk;
        range[i].end   = (i == nthreads - 1) ? n : (i + 1) * chunk;
    }

    double t0 = now_ms();
    for (int i = 0; i < nthreads; i++)
        pthread_create(&tid[i], NULL, fn, &range[i]);
    for (int i = 0; i < nthreads; i++)
        pthread_join(tid[i], NULL);
    double ms = now_ms() - t0;

    double total = 0;
    for (int i = 0; i < nthreads; i++)
        total += partial[i].value;
    *total_out = total;
    return ms;
}

/* Best of REPS runs, to filter out scheduler noise. */
static double best(void *(*fn)(void *), int nthreads, long n, double *total_out)
{
    double b = 0;
    for (int r = 0; r < REPS; r++) {
        double ms = once(fn, nthreads, n, total_out);
        if (r == 0 || ms < b) b = ms;
    }
    return b;
}

/* Print a speedup table for one workload. Returns the speedup at MAXTHREADS. */
static double table(const char *title, void *(*fn)(void *), long n,
                    const char *bytes_note, double expect_total)
{
    printf("== %s ==\n", title);
    if (bytes_note) printf("   %s\n", bytes_note);

    double total;
    /* WARM-UP: touch everything once, untimed. Without this the 1-thread
       baseline is cold and every later measurement looks superlinear. */
    once(fn, 1, n, &total);

    double t1 = 0, last = 0;
    printf("   %8s %10s %10s %12s\n",
           "threads", "best(ms)", "speedup", "efficiency");
    printf("   %8s %10s %10s %12s\n",
           "-------", "--------", "-------", "----------");
    for (int t = 1; t <= MAXTHREADS; t++) {
        double ms = best(fn, t, n, &total);
        if (t == 1) t1 = ms;
        last = t1 / ms;
        int wrong = (expect_total > 0) &&
                    (fabs(total - expect_total) > 1e-6 * expect_total);
        printf("   %8d %10.1f %9.2fx %11.0f%%%s\n",
               t, ms, t1 / ms, 100.0 * (t1 / ms) / t,
               wrong ? "   WRONG TOTAL" : "");
    }
    printf("\n");
    return last;
}

int main(void)
{
    mem_array = malloc(N_MEM * sizeof(long));
    cpu_array = malloc(N_CPU * sizeof(long));
    if (!mem_array || !cpu_array) { perror("malloc"); return 1; }
    for (long i = 0; i < N_MEM; i++) mem_array[i] = 1;
    for (long i = 0; i < N_CPU; i++) cpu_array[i] = (i % 97) + 1;

    char note[160];

    snprintf(note, sizeof(note),
             "%ld elements (%ld MB) -- far larger than any cache, so this "
             "streams from DRAM", N_MEM, N_MEM * (long)sizeof(long) / (1024 * 1024));
    double sp_mem = table("workload A: MEMORY-BOUND (plain sum of a big array)",
                          work_memory, N_MEM, note, (double)N_MEM);

    snprintf(note, sizeof(note),
             "%ld elements (%ld KB, cache-resident) x %d rounds of real "
             "floating-point work", N_CPU, N_CPU * (long)sizeof(long) / 1024,
             CPU_ROUNDS);
    double sp_cpu = table("workload B: COMPUTE-BOUND (arithmetic in cache)",
                          work_compute, N_CPU, note, -1);

    printf("Observations\n------------\n");
    printf("- The SAME parallel structure scaled %.2fx on the memory-bound\n",
           sp_mem);
    printf("  workload and %.2fx on the compute-bound one, at %d threads. The\n",
           sp_cpu, MAXTHREADS);
    printf("  parallelism was identical; what differed is which resource ran\n");
    printf("  out first.\n");
    printf("- Workload A saturates MEMORY BANDWIDTH, which is shared by every\n");
    printf("  core. Once a couple of cores are streaming, the rest queue behind\n");
    printf("  DRAM and extra threads buy almost nothing -- Lecture 9's memory\n");
    printf("  mountain seen from the parallel side. Adding cores cannot add\n");
    printf("  bandwidth.\n");
    printf("- Workload B works out of cache, so cores ARE the limit and it\n");
    printf("  scales much further. Look for the knee near 8 threads: this\n");
    printf("  machine has 8 performance cores and 4 slower efficiency cores\n");
    printf("  (demo 04), so threads 9-12 contribute less than threads 1-8.\n");
    printf("- 'Efficiency' = speedup/threads is the honest column. It falls\n");
    printf("  steadily in both workloads (with some scheduler jitter at the\n");
    printf("  top end): every added core bought less\n");
    printf("  than the one before. That is Amdahl's law and resource\n");
    printf("  saturation, together.\n");
    printf("- Both workloads produced the correct total at every thread count,\n");
    printf("  so none of this is about correctness -- only about speed.\n");
    printf("- Methodological note: these numbers come from a WARM cache with\n");
    printf("  the best of %d runs. An earlier version of this demo measured a\n",
           REPS);
    printf("  cold 1-thread baseline and reported a 9.78x speedup on 2 threads.\n");
    printf("  If a parallel speedup exceeds the core count, suspect the\n");
    printf("  measurement before believing the result.\n");

    free(mem_array);
    free(cpu_array);
    return 0;
}
