// Pointer chasing: hər oxunuş əvvəlki oxunuşun nəticəsindən asılıdır,
// ona görə CPU onları qabaqcadan yükləyə bilmir. Ölçülən vaxt = yaddaşın latency-si.
// İstifadə: ./chase [huge]   huge = 2 MB-lıq huge page istə (TLB təsirini azaldır)
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <time.h>
#include <sys/mman.h>

static double now(void) {
    struct timespec t;
    clock_gettime(CLOCK_MONOTONIC, &t);
    return t.tv_sec + t.tv_nsec / 1e9;
}

static uint64_t rng = 88172645463325252ull;
static uint64_t next_rand(void) {            // xorshift64: sadə təsadüfi ədəd generatoru
    rng ^= rng << 13; rng ^= rng >> 7; rng ^= rng << 17;
    return rng;
}

int main(int argc, char **argv) {
    int huge = argc > 1 && strcmp(argv[1], "huge") == 0;
    for (size_t size = 4 << 10; size <= ((size_t)1 << 30); size *= 2) {
        size_t lines = size / 64;            // hər node ayrı cache line-da
        uint64_t *a = aligned_alloc(2 << 20, size < (2 << 20) ? (2 << 20) : size);
        if (huge) madvise(a, size, MADV_HUGEPAGE);
        // Sattolo alqoritmi: bütün line-lardan keçən bir böyük təsadüfi dövrə
        uint64_t *order = malloc(lines * sizeof(uint64_t));
        for (size_t i = 0; i < lines; i++) order[i] = i;
        for (size_t i = lines - 1; i > 0; i--) {
            size_t j = next_rand() % i;
            uint64_t t = order[i]; order[i] = order[j]; order[j] = t;
        }
        for (size_t i = 0; i < lines; i++)
            a[order[i] * 8] = order[(i + 1) % lines] * 8;   // növbəti node-un indeksi
        free(order);

        size_t steps = 20000000, p = 0;
        for (size_t i = 0; i < lines; i++) p = a[p];        // isinmə
        double t0 = now();
        for (size_t i = 0; i < steps; i++) p = a[p];        // asılı oxunuşlar zənciri
        double t1 = now();
        printf("%9zu KB  %6.1f ns\n", size >> 10, (t1 - t0) / steps * 1e9);
        if (p == 12345) puts("");                            // kompilyator dövrü silməsin
        free(a);
    }
    return 0;
}
