// Build in an x64 Native Tools command prompt:
// cl /O2 /EHsc /std:c++17 flag-scan.cpp
// Or with GCC: g++ -O2 -std=c++17 flag-scan.cpp -o flag-scan
#include <algorithm>
#include <array>
#include <chrono>
#include <cstddef>
#include <cstdint>
#include <iomanip>
#include <iostream>
#include <random>
#include <vector>

struct Entity {
    std::uint8_t active;
    std::uint8_t other_fields[63];
};
static_assert(sizeof(Entity) == 64);

template <class Range, class ReadFlag>
double time_scan(const Range& values, ReadFlag read_flag, std::uint64_t& count) {
    const auto start = std::chrono::steady_clock::now();
    std::uint64_t total = 0;
    for (const auto& value : values) {
        total += read_flag(value);
    }
    const auto end = std::chrono::steady_clock::now();
    count = total;
    return std::chrono::duration<double, std::milli>(end - start).count();
}

constexpr std::size_t samples = 12;
double median(std::array<double, samples> times) {
    std::sort(times.begin(), times.end());
    return (times[samples / 2 - 1] + times[samples / 2]) / 2;
}

int main() {
    constexpr std::size_t size = 1u << 22;
    std::vector<Entity> records(size);
    std::vector<std::uint8_t> flags(size);
    std::mt19937 random(12345);
    std::uint64_t expected = 0;
    for (std::size_t i = 0; i < size; ++i) {
        flags[i] = static_cast<std::uint8_t>(random() & 1u);
        records[i].active = flags[i];
        expected += flags[i];
    }

    std::array<double, samples> record_times{}, flag_times{};
    for (std::size_t round = 0; round <= samples; ++round) {
        // Change one input outside the timed region before each pair.
        const auto index = random() % size;
        expected -= flags[index];
        flags[index] ^= 1;
        records[index].active = flags[index];
        expected += flags[index];

        std::uint64_t record_count = 0, flag_count = 0;
        const auto scan_records = [&] {
            return time_scan(records, [](const Entity& e) { return e.active; }, record_count);
        };
        const auto scan_flags = [&] {
            return time_scan(flags, [](std::uint8_t flag) { return flag; }, flag_count);
        };
        double record_ms, flag_ms;
        if (round % 2 == 0) {
            record_ms = scan_records();
            flag_ms = scan_flags();
        } else {
            flag_ms = scan_flags();
            record_ms = scan_records();
        }
        if (record_count != expected || flag_count != expected) {
            std::cerr << "Count mismatch\n";
            return 1;
        }
        if (round > 0) {
            record_times[round - 1] = record_ms;
            flag_times[round - 1] = flag_ms;
        }
    }

    std::cout << std::fixed << std::setprecision(3)
              << "64-byte records, median ms: " << median(record_times) << '\n'
              << "1-byte flags, median ms: " << median(flag_times) << '\n';
}
