Spaces:
Running
Running
File size: 18,046 Bytes
ef8334d | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 | // 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 <algorithm>
#include <chrono>
#include <cstdint>
#include <cstdlib>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <limits>
#include <list>
#include <numeric>
#include <random>
#include <stdexcept>
#include <string>
#include <vector>
namespace {
using Id = std::uint32_t;
using Rev = std::uint64_t;
using Clock = std::chrono::steady_clock;
constexpr Rev no_poll = std::numeric_limits<Rev>::max();
std::uint64_t ns(Clock::duration d) {
return std::chrono::duration_cast<std::chrono::nanoseconds>(d).count();
}
struct Write { Id id; bool deleted; };
struct Batch { std::vector<Write> writes; Rev cursor = no_poll; };
struct Trace {
std::vector<Id> initial;
std::vector<Batch> 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<Rev> 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<Id>(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<Id>(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<Rev> values;
Rev record(Id id, bool deleted) {
Rev rev = ++head;
values[id] = (rev << 1) | static_cast<Rev>(deleted);
return rev;
}
};
// All ordered scan paths sort copied records by revision, avoiding indirect comparator loads.
template<class Fn> void emit_sorted(std::vector<Entry>& 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<bool Ordered> 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<class Fn> 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<Entry> 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<class Fn> 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<Id>(i)});
}
}
}
emit_sorted(hits, fn);
}
private:
State state;
std::vector<Rev> blocks, supers;
std::vector<Entry> 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<class Fn> 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<Id> ring;
std::vector<Entry> 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<class Fn> 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<Id> 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<Id>(i)}));
}
}
void write(Id id, bool deleted) {
auto pos = nodes[id];
pos->marked = (++head << 1) | static_cast<Rev>(deleted);
list.splice(list.begin(), list, pos);
}
template<class Fn> 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<Entry> list;
std::vector<std::list<Entry>::iterator> nodes;
Rev head = 0;
};
template<class PublicIndex> 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<class Fn> 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<Rev>(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<Digest> polls;
std::vector<Rev> query_times;
Digest final;
Rev elapsed = 0;
};
template<class Engine, bool Sample> 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<Rev>& sorted, unsigned p) {
return sorted[(sorted.size()*p+99)/100-1]; // nearest rank
}
template<class Engine> 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<Engine, false>(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<Engine, true>(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<unsigned>(v);
}
} // namespace
int main(int argc, char** argv) try {
Id slots = 65536;
unsigned reps = 3;
std::uint32_t seed = 739391;
std::vector<std::string> 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<Journal>);
struct Implementation { std::string name; bool ordered; Measure execute; };
const std::vector<Implementation> engines{
{"sincekit", true, measure<Candidate<sincekit::Index>>},
{"scan_sorted", true, measure<Scan<true>>},
{"blocks_sorted", true, measure<Blocks>},
{"journal", true, measure<Journal>},
{"scan_unordered", false, measure<Scan<false>>},
{"std_list", true, measure<StdList>},
{"compact_journal", true, measure<CompactJournal>},
{"sincekit_compact", true, measure<Candidate<sincekit::CompactIndex>>},
};
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<Scan<true>, 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;
}
|