// Build from the project root: c++ -O3 -DNDEBUG -std=c++17 -Iinclude bench/bench.cpp -o /tmp/sincekit-bench // Outputs JSON Lines. Setup, trace generation, verification and storage allocation are untimed. #include "sincekit.h" #include "sincekit_compact.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include namespace { using Id = std::uint32_t; using Rev = std::uint64_t; using Clock = std::chrono::steady_clock; constexpr Rev no_poll = std::numeric_limits::max(); std::uint64_t ns(Clock::duration d) { return std::chrono::duration_cast(d).count(); } struct Write { Id id; bool deleted; }; struct Batch { std::vector writes; Rev cursor = no_poll; }; struct Trace { std::vector initial; std::vector batches; std::size_t write_count = 0; }; Trace make_trace(const std::string& name, Id slots, std::uint32_t seed) { // All engines start with a full population, in the same shuffled revision order. std::mt19937 rng(seed); Trace t; t.initial.resize(slots); std::iota(t.initial.begin(), t.initial.end(), Id{0}); std::shuffle(t.initial.begin(), t.initial.end(), rng); auto shuffled = t.initial; Rev head = slots; std::vector cursors(name == "lagged_hot" ? 128 : 32, head); unsigned rounds = 0; if (name == "idle") rounds = 8192; if (name == "sparse") rounds = 2048; if (name == "hot") rounds = 384; if (name == "lagged_hot") rounds = 8192; if (name == "dense") rounds = 20; if (name == "mixed") rounds = 128; if (name == "write_only") rounds = 64; if (!rounds) throw std::invalid_argument("unknown scenario: " + name); for (unsigned i = 0; i < rounds; ++i) { Batch batch; unsigned writes = 0; unsigned reader = 0; if (name == "sparse") { writes = 2; reader = i % cursors.size(); } else if (name == "hot") { writes = 512; } else if (name == "lagged_hot") { // Interleaved clients have distinct checkpoints. Roughly 1,000 revisions arrive // during each client's absence, all overwriting just 16 slots. writes = 4 + rng() % 9; reader = i % cursors.size(); } else if (name == "dense") { writes = slots; std::shuffle(shuffled.begin(), shuffled.end(), rng); } else if (name == "mixed") { writes = (i % 16 == 0) ? slots / 2 : (rng() % 97); reader = rng() % cursors.size(); } else if (name == "write_only") { writes = std::max(1, slots / 8); } batch.writes.reserve(writes); for (unsigned j = 0; j < writes; ++j) { Id id; if (name == "dense") id = shuffled[j]; else if (name == "hot" || name == "lagged_hot" || (name == "mixed" && (j % 4))) id = t.initial[rng() % std::min(slots, 16)]; else id = rng() % slots; batch.writes.push_back({id, rng() % 8 == 0}); } head += writes; t.write_count += writes; if (name != "write_only") { // Occasionally restart a reader at zero to exercise bounded-history fallback. batch.cursor = (name == "mixed" && (i % 17 == 0)) ? 0 : cursors[reader]; cursors[reader] = head; } t.batches.push_back(std::move(batch)); } return t; } struct Entry { Rev marked; // low bit holds delete, remaining bits hold the revision (bounded benchmark inputs). Id id; }; struct State { explicit State(std::size_t n) : values(n, 0) {} Rev head = 0; std::vector values; Rev record(Id id, bool deleted) { Rev rev = ++head; values[id] = (rev << 1) | static_cast(deleted); return rev; } }; // All ordered scan paths sort copied records by revision, avoiding indirect comparator loads. template void emit_sorted(std::vector& hits, Fn&& fn) { std::sort(hits.begin(), hits.end(), [](const Entry& a, const Entry& b) { return a.marked > b.marked; }); for (auto e : hits) fn(e.id, e.marked >> 1, bool(e.marked & 1)); } template class Scan { public: explicit Scan(std::size_t n) : state(n) { if constexpr (Ordered) hits.reserve(n); } void write(Id id, bool del) { state.record(id, del); } template void since(Rev cursor, Fn&& fn) { if (cursor == state.head) return; if constexpr (Ordered) hits.clear(); for (Id i = 0; i < state.values.size(); ++i) { Rev marked = state.values[i]; if ((marked >> 1) <= cursor) continue; if constexpr (Ordered) hits.push_back({marked, i}); else fn(i, marked >> 1, bool(marked & 1)); } if constexpr (Ordered) emit_sorted(hits, fn); } private: State state; std::vector hits; }; // Max revision per 64-slot block and per 64-block superblock. Updated maxima only increase. class Blocks { public: explicit Blocks(std::size_t n) : state(n), blocks((n+63)/64), supers((blocks.size()+63)/64) { hits.reserve(n); } void write(Id id, bool del) { Rev rev = state.record(id, del); blocks[id / 64] = rev; supers[id / 4096] = rev; } template void since(Rev cursor, Fn&& fn) { if (cursor == state.head) return; hits.clear(); for (std::size_t s = 0; s < supers.size(); ++s) { if (supers[s] <= cursor) continue; auto end_block = std::min(blocks.size(), (s+1)*64); for (std::size_t b = s*64; b < end_block; ++b) { if (blocks[b] <= cursor) continue; auto end_id = std::min(state.values.size(), (b+1)*64); for (std::size_t i = b*64; i < end_id; ++i) { Rev m = state.values[i]; if ((m >> 1) > cursor) hits.push_back({m, static_cast(i)}); } } } emit_sorted(hits, fn); } private: State state; std::vector blocks, supers; std::vector hits; }; std::size_t journal_capacity(std::size_t slots) { std::size_t n = 1; while (n < slots*2) n *= 2; return n; } class Journal { public: explicit Journal(std::size_t n) : state(n), ring(journal_capacity(n)) { hits.reserve(n); } void write(Id id, bool del) { Rev rev = state.record(id, del); ring[(rev-1) & (ring.size()-1)] = id; } template void since(Rev cursor, Fn&& fn) { if (state.head - cursor <= ring.size()) { for (Rev r = state.head; r > cursor; --r) { Id i = ring[(r-1) & (ring.size()-1)]; Rev marked = state.values[i]; // Current revision per slot is the generation array. Superseded entries fail this test. if ((marked >> 1) == r) fn(i, r, bool(marked & 1)); } return; } hits.clear(); for (Id i = 0; i < state.values.size(); ++i) { Rev m = state.values[i]; if ((m >> 1) > cursor) hits.push_back({m, i}); } emit_sorted(hits, fn); } private: State state; std::vector ring; std::vector hits; }; // Two generations survive arbitrarily old cursors without sorting. The compacted // prefix contains each slot once in chronological order; the active tail uses // contiguous revision numbers and can discard superseded entries at read time. class CompactJournal { public: explicit CompactJournal(std::size_t n) : state(n) { prefix.reserve(n); tail.reserve(n); } void write(Id id, bool del) { if (tail.size() == state.values.size()) compact(); state.record(id, del); tail.push_back(id); } template void since(Rev cursor, Fn&& fn) { if (cursor == state.head) return; Rev r = state.head; for (auto i = tail.rbegin(); i != tail.rend(); ++i, --r) { if (r <= cursor) return; Rev m = state.values[*i]; if ((m >> 1) == r) fn(*i, r, bool(m & 1)); } if (prefix_rev <= cursor) return; for (auto i = prefix.rbegin(); i != prefix.rend(); ++i) { Rev m = state.values[*i]; Rev last = m >> 1; if (last > prefix_rev) continue; if (last <= cursor) break; fn(*i, last, bool(m & 1)); } } private: void compact() { std::size_t survivors = 0; for (Id id : prefix) { if ((state.values[id] >> 1) <= prefix_rev) prefix[survivors++] = id; } prefix.resize(survivors); Rev r = prefix_rev; for (Id id : tail) { ++r; if ((state.values[id] >> 1) == r) prefix.push_back(id); } prefix_rev = state.head; tail.clear(); } State state; Rev prefix_rev = 0; std::vector prefix, tail; }; // Standard-library implementation of the same move-to-front algorithm. Every slot has a // preallocated list node and a direct iterator, so timing never includes list allocation. class StdList { public: explicit StdList(std::size_t n) { nodes.reserve(n); for (std::size_t i = 0; i < n; ++i) { nodes.push_back(list.insert(list.end(), {0, static_cast(i)})); } } void write(Id id, bool deleted) { auto pos = nodes[id]; pos->marked = (++head << 1) | static_cast(deleted); list.splice(list.begin(), list, pos); } template void since(Rev cursor, Fn&& fn) { if (cursor == head) return; for (const Entry& e : list) { Rev r = e.marked >> 1; if (r <= cursor) break; fn(e.id, r, bool(e.marked & 1)); } } private: std::list list; std::vector::iterator> nodes; Rev head = 0; }; template class Candidate { public: explicit Candidate(std::size_t n) : index(n) {} void write(Id id, bool del) { if (del) index.erase(id); else index.touch(id); } template void since(Rev c, Fn&& fn) { index.since(c, fn); } private: PublicIndex index; }; struct Digest { Rev count = 0, sum = 0, order = 0; void add(Id id, Rev r, bool del) { Rev v = r * 0x9e3779b97f4a7c15ULL ^ (Rev(id) << 1) ^ static_cast(del); ++count; sum += v; order = order * 31 + v; } bool same(const Digest& x, bool ordered) const { return count == x.count && sum == x.sum && (!ordered || order == x.order); } }; struct Trial { std::vector polls; std::vector query_times; Digest final; Rev elapsed = 0; }; template Trial run(const Trace& t) { Engine engine(t.initial.size()); for (Id id : t.initial) engine.write(id, false); // Prime any reusable query workspace before timing. A caller can repeatedly use every engine. engine.since(0, [](Id, Rev, bool) {}); Trial trial; trial.polls.reserve(t.batches.size()); if constexpr (Sample) trial.query_times.reserve(t.batches.size()); const auto start = Clock::now(); for (auto& batch : t.batches) { for (auto w : batch.writes) engine.write(w.id, w.deleted); if (batch.cursor != no_poll) { Digest d; Clock::time_point qstart; if constexpr (Sample) qstart = Clock::now(); engine.since(batch.cursor, [&](Id id, Rev r, bool del) { d.add(id, r, del); }); if constexpr (Sample) trial.query_times.push_back(ns(Clock::now()-qstart)); trial.polls.push_back(d); } } trial.elapsed = ns(Clock::now()-start); // Observe final state even for writes-only, where no change query runs inside the timer. engine.since(0, [&](Id id, Rev r, bool del) { trial.final.add(id, r, del); }); return trial; } void verify(const Trial& t, const Trial& ref, bool ordered) { if (t.polls.size() != ref.polls.size() || !t.final.same(ref.final, ordered)) throw std::runtime_error("final state or poll count mismatch"); for (std::size_t i = 0; i < t.polls.size(); ++i) if (!t.polls[i].same(ref.polls[i], ordered)) throw std::runtime_error("digest mismatch at poll " + std::to_string(i)); } Rev percentile(const std::vector& sorted, unsigned p) { return sorted[(sorted.size()*p+99)/100-1]; // nearest rank } template void measure(const std::string& label, bool ordered, const std::string& scenario, const Trace& trace, unsigned rep, std::uint32_t seed, const Trial& ref) { auto all = run(trace); verify(all, ref, ordered); Rev emitted = 0; for (auto d : all.polls) emitted += d.count; std::cout << "{\"kind\":\"trial\",\"scenario\":" << std::quoted(scenario) << ",\"engine\":" << std::quoted(label) << ",\"ordered\":" << (ordered ? "true" : "false") << ",\"rep\":" << rep << ",\"seed\":" << seed << ",\"slots\":" << trace.initial.size() << ",\"writes\":" << trace.write_count << ",\"polls\":" << all.polls.size() << ",\"emitted\":" << emitted << ",\"batch_ns\":" << all.elapsed; if (!all.polls.empty()) { auto sampled = run(trace); verify(sampled, ref, ordered); std::sort(sampled.query_times.begin(), sampled.query_times.end()); std::cout << ",\"poll_p50_ns\":" << percentile(sampled.query_times, 50) << ",\"poll_p99_ns\":" << percentile(sampled.query_times, 99) << ",\"poll_max_ns\":" << sampled.query_times.back(); } std::cout << ",\"final_digest\":\"" << std::hex << all.final.sum << std::dec << "\"}\n"; } std::string proc_field(const std::string& path, const std::string& field) { std::ifstream stream(path); for (std::string line; std::getline(stream, line);) { auto sep = line.find(':'); if (line.substr(0, sep).find(field) == 0 && sep != std::string::npos) { auto first = line.find_first_not_of(" \t", sep+1); if (first != std::string::npos) return line.substr(first); } } return "unknown"; } unsigned number(const char* s, unsigned min, unsigned max) { std::string str(s); std::size_t consumed = 0; auto v = std::stoull(str, &consumed); if (consumed != str.size() || v < min || v > max) throw std::out_of_range("numeric option out of range"); return static_cast(v); } } // namespace int main(int argc, char** argv) try { Id slots = 65536; unsigned reps = 3; std::uint32_t seed = 739391; std::vector scenarios{"idle", "sparse", "hot", "lagged_hot", "dense", "mixed", "write_only"}; std::string selected_engine; for (int i = 1; i < argc; ++i) { std::string opt(argv[i]); if (opt == "--help") { std::cout << "sincekit-bench [--slots N] [--reps N] [--seed N] " "[--engine NAME] [--scenario idle|sparse|hot|lagged_hot|dense|mixed|write_only]\n"; return 0; } if (++i >= argc) throw std::invalid_argument("missing argument for " + opt); if (opt == "--slots") slots = number(argv[i], 1, 1U<<24); else if (opt == "--reps") reps = number(argv[i], 1, 1000); else if (opt == "--seed") seed = number(argv[i], 0, UINT32_MAX); else if (opt == "--scenario") scenarios = {argv[i]}; else if (opt == "--engine") selected_engine = argv[i]; else throw std::invalid_argument("unknown option: " + opt); } std::cout << "{\"kind\":\"environment\",\"compiler\":" << std::quoted(__VERSION__) << ",\"cplusplus\":" << __cplusplus << ",\"cpu\":" << std::quoted(proc_field("/proc/cpuinfo","model name")) << ",\"allowed_cpus\":" << std::quoted(proc_field("/proc/self/status","Cpus_allowed_list")) << ",\"clock\":\"steady_clock\",\"journal_capacity\":" << journal_capacity(slots) << ",\"reps\":" << reps << ",\"slots\":" << slots << ",\"seed\":" << seed << "}\n"; using Measure = decltype(&measure); struct Implementation { std::string name; bool ordered; Measure execute; }; const std::vector engines{ {"sincekit", true, measure>}, {"scan_sorted", true, measure>}, {"blocks_sorted", true, measure}, {"journal", true, measure}, {"scan_unordered", false, measure>}, {"std_list", true, measure}, {"compact_journal", true, measure}, {"sincekit_compact", true, measure>}, }; if (!selected_engine.empty() && std::none_of(engines.begin(), engines.end(), [&](auto& e){ return e.name == selected_engine; })) { throw std::invalid_argument("unknown engine: " + selected_engine); } // A fresh reference checks every query in every trial. Rotate engine order to limit warmup bias. for (unsigned s = 0; s < scenarios.size(); ++s) { auto& scenario = scenarios[s]; auto trace = make_trace(scenario, slots, seed); auto ref = run, false>(trace); for (unsigned rep = 0; rep < reps; ++rep) { for (std::size_t i = 0; i < engines.size(); ++i) { const auto& e = engines[(i+rep+s) % engines.size()]; if (selected_engine.empty() || selected_engine == e.name) e.execute(e.name, e.ordered, scenario, trace, rep, seed, ref); } } } } catch (const std::exception& e) { std::cerr << e.what() << '\n'; return 1; }