// SPDX-License-Identifier: MIT
// Small controlled experiments; see README.md for scope and methodology.
#include <algorithm>
#include <array>
#include <atomic>
#include <barrier>
#include <chrono>
#include <cstdint>
#include <cstdlib>
#include <iomanip>
#include <iostream>
#include <memory>
#include <numeric>
#include <random>
#include <stdexcept>
#include <string>
#include <thread>
#include <vector>

using Clock = std::chrono::steady_clock;
#if defined(__GNUC__) || defined(__clang__)
#define NOINLINE __attribute__((noinline))
#else
#define NOINLINE
#endif
struct Result { std::uint64_t checksum; std::size_t allocations = 0; };
struct Sample { double ms; Result result; };
static std::atomic<std::uint64_t> sink{0};

template<class F> Sample timed(F&& fn) {
    const auto start = Clock::now();
    const Result result = fn();
    const double ms = std::chrono::duration<double, std::milli>(Clock::now()-start).count();
    sink.fetch_xor(result.checksum, std::memory_order_relaxed);
    return {ms, result};
}
void emit(const char* id, std::size_t config, const char* variant, int trial,
          const Sample& sample, std::uint64_t expected) {
    if (sample.result.checksum != expected) throw std::runtime_error("checksum mismatch");
    std::cout << "{\"experiment\":\"" << id << "\",\"config\":" << config
              << ",\"variant\":\"" << variant << "\",\"trial\":" << trial
              << ",\"ms\":" << std::setprecision(12) << sample.ms
              << ",\"checksum\":\"" << sample.result.checksum
              << "\",\"allocations\":" << sample.result.allocations << "}\n";
}
// Both variants execute the same dependent traversal, with different successor links.
struct Node { std::uint32_t next; std::uint64_t value; };
static_assert(sizeof(Node) == 16, "recorded workload requires 16-byte nodes");
NOINLINE Result traverse(const std::vector<Node>& nodes, std::uint32_t head, std::size_t rounds) {
    std::uint64_t sum = 0;
    auto at = head;
    for (std::size_t r=0; r<rounds; ++r)
        for (std::size_t i=0; i<nodes.size(); ++i) {
            const auto& node = nodes[at]; sum += node.value; at = node.next;
        }
    return {sum};
}
void locality(std::size_t count, int trials, bool verify) {
    std::vector<Node> sequential(count), shuffled(count);
    std::vector<std::uint32_t> order(count);
    std::iota(order.begin(), order.end(), 0);
    // Explicit Fisher-Yates with a fixed engine; independent of std::shuffle implementation.
    std::mt19937 rng(42);
    for (std::size_t i=count-1; i>0; --i) std::swap(order[i], order[rng()%(i+1)]);
    for (std::size_t i=0; i<count; ++i) {
        sequential[i] = {static_cast<std::uint32_t>((i+1)%count), i+1};
        shuffled[i].value = i+1;
        shuffled[order[i]].next = order[(i+1)%count];
    }
    const std::size_t rounds = verify ? 2 : std::max<std::size_t>(1, 2097152/count);
    const auto expected = std::uint64_t(count)*(count+1)/2*rounds;
    for (int t=-2; t<trials; ++t) for (int j=0; j<2; ++j) {
        const bool compact = ((j+(t+2))%2)==0;
        auto s = timed([&]{ return compact ? traverse(sequential,0,rounds) : traverse(shuffled,order[0],rounds); });
        if (s.result.checksum != expected) throw std::runtime_error("locality mismatch");
        if (t>=0) emit("locality",count,compact?"sequential":"shuffled",t,s,expected);
    }
}

// Packed counters occupy one aligned 64-byte region on this workload.
// Padded counters are separated by 128 bytes. Actual cache-line size is host dependent.
static_assert(sizeof(std::atomic<std::uint64_t>) == 8);
struct alignas(128) Padded { std::atomic<std::uint64_t> value{0}; };
Sample counters(std::size_t workers, std::size_t iterations, bool separate) {
    alignas(128) std::array<std::atomic<std::uint64_t>,8> packed{};
    std::array<Padded,8> padded{};
    std::barrier ready(static_cast<std::ptrdiff_t>(workers+1));
    std::barrier start(static_cast<std::ptrdiff_t>(workers+1));
    std::barrier done(static_cast<std::ptrdiff_t>(workers+1));
    std::vector<std::thread> threads;
    threads.reserve(workers);
    for (std::size_t i=0; i<workers; ++i) threads.emplace_back([&,i]{
        auto& counter = separate ? padded[i].value : packed[i];
        ready.arrive_and_wait(); start.arrive_and_wait();
        for (std::size_t k=0; k<iterations; ++k) counter.fetch_add(1,std::memory_order_relaxed);
        done.arrive_and_wait();
    });
    ready.arrive_and_wait();
    const auto begin = Clock::now();
    start.arrive_and_wait(); done.arrive_and_wait();
    const double ms = std::chrono::duration<double,std::milli>(Clock::now()-begin).count();
    for (auto& thread:threads) thread.join();
    std::uint64_t sum=0;
    for (std::size_t i=0;i<workers;++i) sum+=(separate?padded[i].value:packed[i]).load();
    sink.fetch_xor(sum,std::memory_order_relaxed);
    return {ms,{sum}};
}
void sharing(std::size_t workers, int trials, bool verify) {
    const std::size_t iterations=verify?1000:1000000;
    const auto expected=workers*iterations;
    for (int t=-2;t<trials;++t) for(int j=0;j<2;++j) {
        const bool separate=((j+(t+2))%2)==0;
        auto s=counters(workers,iterations,separate);
        if(s.result.checksum!=expected) throw std::runtime_error("counter mismatch");
        if(t>=0) emit("sharing",workers,separate?"padded":"packed",t,s,expected);
    }
}

static std::size_t allocation_count=0;
template<class T> struct CountingAllocator {
    using value_type=T;
    CountingAllocator() = default;
    template<class U> CountingAllocator(const CountingAllocator<U>&) {}
    T* allocate(std::size_t n) { ++allocation_count; return std::allocator<T>{}.allocate(n); }
    void deallocate(T* p,std::size_t n) { std::allocator<T>{}.deallocate(p,n); }
    template<class U> bool operator==(const CountingAllocator<U>&) const { return true; }
};
using Buffer=std::vector<std::uint64_t,CountingAllocator<std::uint64_t>>;
NOINLINE std::uint64_t fill_and_sum(Buffer& data, std::size_t size, std::uint64_t batch) {
    data.resize(size);
    for(std::size_t i=0;i<size;++i) data[i]=i+batch;
    const auto result=std::accumulate(data.begin(),data.end(),std::uint64_t{0});
    data.clear(); return result;
}
NOINLINE Result allocating(std::size_t size,std::size_t batches,Buffer& reused,bool reuse) {
    const auto before=allocation_count;
    std::uint64_t sum=0;
    for(std::size_t b=0;b<batches;++b) {
        if(reuse) sum+=fill_and_sum(reused,size,b);
        else { Buffer temporary; sum+=fill_and_sum(temporary,size,b); }
    }
    return {sum,allocation_count-before};
}
void allocation(std::size_t size,int trials,bool verify) {
    const std::size_t batches=verify?20:10000;
    const auto expected=std::uint64_t(batches)*size*(size-1)/2+std::uint64_t(size)*batches*(batches-1)/2;
    Buffer reused; reused.reserve(size); // Steady-state experiment; setup allocation excluded.
    for(int t=-2;t<trials;++t) for(int j=0;j<2;++j) {
        const bool reuse=((j+(t+2))%2)==0;
        auto s=timed([&]{ return allocating(size,batches,reused,reuse); });
        if(s.result.checksum!=expected || s.result.allocations!=(reuse?0:batches))
            throw std::runtime_error("allocation/checksum mismatch");
        if(t>=0) emit("allocation",size,reuse?"reuse":"fresh",t,s,expected);
    }
}
int main(int argc,char** argv) {
    try {
        const bool verify=argc==2 && std::string(argv[1])=="--verify";
        if(argc>1 && !verify) throw std::runtime_error("usage: perf-playground [--verify]");
        const int trials=verify?1:7;
        for(auto n: verify?std::vector<std::size_t>{16,257,4096}:std::vector<std::size_t>{4096,65536,1048576}) locality(n,trials,verify);
        for(auto n:{2u,4u}) sharing(n,trials,verify);
        for(auto n:{32u,256u,2048u}) allocation(n,trials,verify);
    } catch(const std::exception& e) { std::cerr<<e.what()<<'\n'; return 1; }
}
