perf_features/perf_features.rs
1//! Feature classification bench. Each feature's representative op is swept
2//! across three queue SIZES, `classify_feature` DECIDES the category from the
3//! shape of that sweep, and the decision plus a measured `p99ByStage` is
4//! merge-written into `.subms/features/rust.json`.
5//!
6//! Resident elements is the sweep axis: for the linked variants it is the number
7//! of nodes the queue holds, for the ring variants the ring's capacity with half
8//! of it occupied. 4096 / 32768 / 262144 elements is a 64x span that walks a
9//! linked queue's live set from 160 KiB to 10 MiB and a ring from 64 KiB to
10//! 4 MiB, so it crosses out of L1 and out of L2. Enqueue and dequeue are O(1) by
11//! construction, so a FLAT curve is the expected answer and a rising one would
12//! be the finding; what the sweep guards against is a feature whose bookkeeping
13//! walks the queue.
14//!
15//! Two measurement units, deliberately:
16//!
17//! - The SWEEP times a sample of `ITEMS_PER_SAMPLE` round trips, not one op. An
18//! enqueue costs a few ns and the platform clock this bench was developed on
19//! ticks at 100 ns, so a single-op p50 reads exactly 100 or 200 ns and the
20//! category is decided by which side of a tick boundary the op lands on. That
21//! is not a hypothetical: measured one op at a time, `metrics` flipped between
22//! hot-path and auxiliary on consecutive runs of unchanged code. Folding a
23//! thousand round trips into one sample puts the sample tens of microseconds
24//! above the tick, and the same run then separates the ring variants from the
25//! allocating base by a clear margin.
26//! - `p99ByStage` times ONE op, the way every other recipe's manifest does, so
27//! the numbers stay comparable across the cookbook. Those figures are only
28//! published from a fleet capture, where the clock has ~1 ns resolution.
29//!
30//! A sample covers the same ITEM count in every feature, `batch` included, whose
31//! calls are `BATCH` items wide. Comparing a 256-item drain against a 1-item pop
32//! would compare batch sizes, not features - and cost per item moved is exactly
33//! the comparison the batch feature exists to win.
34//!
35//! Every queue is pre-filled and every measured unit is a round trip, so
36//! occupancy is a fixed fraction at every sweep point and the ring variants
37//! never take their full or empty branch (`bounded`'s reject path is measured
38//! separately, as its own stage).
39//!
40//! The multi-producer variants are measured SINGLE-THREADED. That isolates the
41//! CAS and the counter indirection from the contention they exist to survive; a
42//! contended number here would say more about the thread count and the box than
43//! about the feature, and what contention buys is a throughput property that no
44//! per-op p99 states.
45//!
46//! This replaces the previous shape, which ran every variant at ONE size and
47//! ASSERTED hot-path via `SubMsStageKind::HotPath`. An asserted category is an
48//! opinion the bench cannot contradict; a sweep measures it, and can disagree.
49//!
50//! These p99 figures describe THIS machine. They are published only when the
51//! manifest is stamped `p99_source: fleet`; a local run leaves the category,
52//! which is machine independent, and no published number.
53//!
54//! Run:
55//! cargo run --release --example perf_features \
56//! --features "harness mpmc bounded batch metrics affinity"
57
58use std::collections::BTreeMap;
59use std::hint::black_box;
60use std::io::{self, Write};
61use std::path::PathBuf;
62
63use subms::{
64 SubMsFeatureManifest, SubMsP99Source, SubMsPerfHarness, SubMsStage, classify_feature, summarize,
65};
66use subms_mpsc_queue::MpscQueue;
67
68/// Resident elements (ring capacity for the bounded variants). A 64x span.
69const SIZES: [usize; 3] = [4_096, 32_768, 262_144];
70const CANON: usize = SIZES[SIZES.len() - 1];
71/// Items moved inside ONE timed sample. Fixed across every feature so the
72/// base-delta test compares cost per item moved.
73const ITEMS_PER_SAMPLE: usize = 1_024;
74/// Timed samples per sweep point.
75const SAMPLES: usize = 256;
76/// Interleaved measurements per sweep point; the lowest is what gets classified.
77const SWEEP_REPEATS: usize = 5;
78/// Items per batch call. FIXED across the sweep - varying it would sweep the
79/// batch size rather than the queue.
80const BATCH: usize = 256;
81/// Single-op reps behind each `p99ByStage` figure.
82const OPS: usize = 50_000;
83/// Warmup is TIME-BOXED, not a fixed rep count. Rust has no JIT, but every one
84/// of these queues either allocates per push or streams a ring array, and both
85/// have a first-touch ramp: measured cold, the first sweep point carries the
86/// page faults for all three and the curve FALLS with size - as wrong as a fake
87/// rise, and harder to spot.
88const WARM_NANOS: u64 = 300_000_000;
89const WARM_MAX_SAMPLES: usize = 5_000;
90/// One-off burn before the first measurement, so the process-level ramp lands
91/// somewhere other than the first sweep point.
92const BURN_NANOS: u64 = 1_000_000_000;
93
94fn stat(h: &SubMsPerfHarness, median: bool) -> u64 {
95 summarize(h)
96 .stages
97 .iter()
98 .find(|s| s.name == "op")
99 .map_or(0, |s| if median { s.p50_ns } else { s.p99_ns })
100}
101
102/// p50 ns of one timed sample covering `reps` calls of `op`.
103fn batched(reps: usize, mut op: impl FnMut(usize)) -> u64 {
104 let mut i = 0usize;
105 let start = std::time::Instant::now();
106 for _ in 0..WARM_MAX_SAMPLES {
107 for _ in 0..reps {
108 op(i);
109 i += 1;
110 }
111 if start.elapsed().as_nanos() as u64 >= WARM_NANOS {
112 break;
113 }
114 }
115 let mut h = SubMsPerfHarness::new("mpsc-queue-feature", "rust");
116 let st = h.stage("op", SAMPLES);
117 for _ in 0..SAMPLES {
118 st.time(|| {
119 for _ in 0..reps {
120 op(i);
121 i += 1;
122 }
123 });
124 }
125 stat(&h, true)
126}
127
128/// p99 ns of a single timed op. `body` is handed the stage so it can put the
129/// restoring half of the round trip OUTSIDE the timed region: without that, a
130/// 50k-op enqueue pass drifts the queue off its steady-state depth and a bounded
131/// ring ends up measuring its full branch instead of the fast path.
132fn single(mut body: impl FnMut(&mut SubMsStage, usize)) -> u64 {
133 let mut warm = SubMsPerfHarness::new("mpsc-queue-feature", "rust");
134 {
135 let st = warm.stage("op", OPS);
136 for i in 0..OPS {
137 body(&mut *st, i);
138 }
139 }
140 let mut h = SubMsPerfHarness::new("mpsc-queue-feature", "rust");
141 {
142 let st = h.stage("op", OPS);
143 for i in 0..OPS {
144 body(&mut *st, i);
145 }
146 }
147 stat(&h, false)
148}
149
150/// Sweeps and PRINTS the curve, both the figures it returns and the raw repeats
151/// behind them. A ratio-compressed or non-monotonic curve classifies flat, and
152/// the rows are the only place that shows up.
153///
154/// Every size is measured `SWEEP_REPEATS` times, INTERLEAVED (all three sizes,
155/// then all three again), and the LOWEST is taken. Two reasons, both visible in
156/// the repeats this prints:
157///
158/// - Measuring one size to completion before moving on aliases slow drift onto
159/// the size axis. Unpinned, this box alternates between two clock states 1.31x
160/// apart and holds each for longer than a measurement takes, which is three
161/// times the delta being classified and enough on its own to flip a feature.
162/// Interleaving spreads that across all three points instead of concentrating
163/// it in one.
164/// - The lowest run is the one least disturbed by the box, and disturbance here
165/// is one-sided: a collection, a migration or a frequency drop only ever adds
166/// time. An average carries the interference into the comparison; the minimum
167/// compares the queues. The p99 figures in `p99ByStage` still come from an
168/// ordinary timed pass, interference included - it is the CATEGORY decision,
169/// not the published latency, that wants the undisturbed number.
170fn sweep(label: &str, mut at: impl FnMut(usize) -> u64) -> Vec<(usize, u64)> {
171 let mut runs = vec![Vec::with_capacity(SWEEP_REPEATS); SIZES.len()];
172 for _ in 0..SWEEP_REPEATS {
173 for (k, &n) in SIZES.iter().enumerate() {
174 runs[k].push(at(n));
175 }
176 }
177 let rows: Vec<(usize, u64)> = SIZES
178 .iter()
179 .enumerate()
180 .map(|(k, &n)| (n, runs[k].iter().copied().min().unwrap_or(0)))
181 .collect();
182 eprintln!("sweep {label}: {rows:?} repeats {runs:?}");
183 rows
184}
185
186/// The base queue holding `n` nodes.
187fn filled(n: usize) -> MpscQueue<u64> {
188 let q = MpscQueue::new();
189 for i in 0..n {
190 q.push(i as u64);
191 }
192 q
193}
194
195fn main() -> io::Result<()> {
196 let path = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
197 .join("..")
198 .join(".subms")
199 .join("features")
200 .join("rust.json");
201 let existing = std::fs::read_to_string(&path).unwrap_or_default();
202 let mut manifest = SubMsFeatureManifest::load_str("rust", &existing);
203 // Stamp the box these numbers came from. The bench runs wherever it is
204 // invoked, so an unstamped manifest is indistinguishable from a fleet
205 // capture; the renderer will not publish one it cannot attribute.
206 let (source, instance) = SubMsP99Source::from_env();
207 manifest.set_p99_source(source, instance.as_deref());
208
209 // Optional, off by default: pin this thread to one core for the whole run.
210 // On a heterogeneous laptop the scheduler moves the bench between core
211 // clusters and every measurement lands in one of two clock states 1.31x
212 // apart - a spread three times wider than the deltas being classified, and
213 // large enough on its own to flip a feature between auxiliary and hot-path.
214 // Pinned, the same sweep repeats to within 1%. Left OFF by default because a
215 // fleet box isolates cores outside the process, and pinning from in here
216 // would override that placement with a core the orchestrator did not choose.
217 #[cfg(feature = "affinity")]
218 if let Some(core) = std::env::var("SUBMS_PIN").ok().and_then(|v| v.parse().ok()) {
219 let _ = subms_mpsc_queue::set_affinity(&[core]);
220 }
221
222 // Burn before the first measurement, not just before each one. Every
223 // `batched` call warms itself, but the FIRST measurement in the process pays
224 // a ramp the per-measurement warm sits inside rather than absorbs, and the
225 // sweep runs smallest-first: without this the base curve read 71800 / 45300 /
226 // 46500 ns, a 1.6x fall with size that is the process settling, not the
227 // queue.
228 {
229 let mut q = filled(CANON);
230 let start = std::time::Instant::now();
231 while (start.elapsed().as_nanos() as u64) < BURN_NANOS {
232 for i in 0..ITEMS_PER_SAMPLE {
233 q.push(i as u64);
234 black_box(q.try_pop());
235 }
236 }
237 }
238
239 // The baseline: the base queue's push + try_pop round trip. Swept as well as
240 // sampled, because whether queue depth moves the BASE op is the context
241 // every feature curve is read against.
242 let base_sweep = sweep("base/push+pop", |n| {
243 let mut q = filled(n);
244 batched(ITEMS_PER_SAMPLE, |i| {
245 q.push(i as u64);
246 black_box(q.try_pop());
247 })
248 });
249 let base_p50 = base_sweep
250 .iter()
251 .find(|(n, _)| *n == CANON)
252 .map_or(0, |(_, v)| *v);
253 eprintln!("base push+pop p50 per {ITEMS_PER_SAMPLE}-item sample: {base_p50}ns");
254
255 // ---------- bounded: fixed-capacity ring, backpressure on enqueue ----------
256 #[cfg(feature = "bounded")]
257 {
258 use subms_mpsc_queue::BoundedMpscQueue;
259 // Half full at every sweep point. Filled to a FIXED element count
260 // instead, the big rings would sit 98% empty and the enqueue would be
261 // measuring the fill fraction rather than the footprint.
262 fn ring(n: usize) -> BoundedMpscQueue<u64> {
263 let q = BoundedMpscQueue::new(n);
264 for i in 0..n / 2 {
265 let _ = q.try_enqueue(i as u64);
266 }
267 q
268 }
269 let sw = sweep("bounded/enqueue+dequeue", |n| {
270 let mut q = ring(n);
271 batched(ITEMS_PER_SAMPLE, |i| {
272 let _ = q.try_enqueue(i as u64);
273 black_box(q.try_dequeue());
274 })
275 });
276 let (cat, reason) = classify_feature(&sw, Some(base_p50), None);
277
278 let mut q = ring(CANON);
279 let mut p99 = BTreeMap::new();
280 p99.insert(
281 "enqueue".to_string(),
282 single(|st, i| {
283 st.time(|| {
284 let _ = q.try_enqueue(i as u64);
285 });
286 black_box(q.try_dequeue());
287 }),
288 );
289 p99.insert(
290 "dequeue".to_string(),
291 single(|st, i| {
292 let _ = q.try_enqueue(i as u64);
293 st.time(|| black_box(q.try_dequeue()));
294 }),
295 );
296 // The reject path, which is the reason the feature exists. The ring is
297 // filled to capacity once, OUTSIDE the timed region; every timed call
298 // then takes the full branch and hands the value back to the caller.
299 let full: BoundedMpscQueue<u64> = BoundedMpscQueue::new(CANON);
300 while full.try_enqueue(0).is_ok() {}
301 p99.insert(
302 "enqueue_full".to_string(),
303 single(|st, i| {
304 st.time(|| {
305 let _ = full.try_enqueue(i as u64);
306 });
307 }),
308 );
309 manifest.set_feature("bounded", cat, &p99, &reason);
310 }
311
312 // ---------- mpmc: bounded ring, sequence CAS on both ends ----------
313 #[cfg(feature = "mpmc")]
314 {
315 use subms_mpsc_queue::MpmcQueue;
316 fn ring(n: usize) -> MpmcQueue<u64> {
317 let q = MpmcQueue::new(n);
318 for i in 0..n / 2 {
319 let _ = q.try_enqueue(i as u64);
320 }
321 q
322 }
323 // Uncontended, so every CAS succeeds first try. That is the figure the
324 // category is about: what the multi-consumer claim costs a queue that is
325 // NOT contended, which is the state a well-sized pipeline runs in.
326 let sw = sweep("mpmc/enqueue+dequeue", |n| {
327 let q = ring(n);
328 batched(ITEMS_PER_SAMPLE, |i| {
329 let _ = q.try_enqueue(i as u64);
330 black_box(q.try_dequeue());
331 })
332 });
333 let (cat, reason) = classify_feature(&sw, Some(base_p50), None);
334
335 let q = ring(CANON);
336 let mut p99 = BTreeMap::new();
337 p99.insert(
338 "enqueue".to_string(),
339 single(|st, i| {
340 st.time(|| {
341 let _ = q.try_enqueue(i as u64);
342 });
343 black_box(q.try_dequeue());
344 }),
345 );
346 p99.insert(
347 "dequeue".to_string(),
348 single(|st, i| {
349 let _ = q.try_enqueue(i as u64);
350 st.time(|| black_box(q.try_dequeue()));
351 }),
352 );
353 manifest.set_feature("mpmc", cat, &p99, &reason);
354 }
355
356 // ---------- batch: drain up to BATCH items behind one acquire fence ----------
357 #[cfg(feature = "batch")]
358 {
359 use subms_mpsc_queue::BatchMpscQueue;
360 fn filled_batch(n: usize) -> BatchMpscQueue<u64> {
361 let q = BatchMpscQueue::new();
362 for i in 0..n {
363 q.push(i as u64);
364 }
365 q
366 }
367 // A sample moves ITEMS_PER_SAMPLE items either way; only the call width
368 // differs. That is why the reps count is divided rather than the batch
369 // grown - growing it would sweep the batch size, and the number would
370 // stop being comparable to the base round trip.
371 let sw = sweep("batch/push+dequeue_batch", |n| {
372 let mut q = filled_batch(n);
373 let mut buf: Vec<Option<u64>> = (0..BATCH).map(|_| None).collect();
374 batched(ITEMS_PER_SAMPLE / BATCH, |i| {
375 for j in 0..BATCH {
376 q.push((i + j) as u64);
377 }
378 black_box(q.try_dequeue_batch(&mut buf));
379 })
380 });
381 let (cat, reason) = classify_feature(&sw, Some(base_p50), None);
382
383 let mut q = filled_batch(CANON);
384 let mut buf: Vec<Option<u64>> = (0..BATCH).map(|_| None).collect();
385 let mut p99 = BTreeMap::new();
386 // The refill is outside the timed region: timing it would put a BATCH of
387 // pushes inside the drain's number and the stage would stop being a
388 // drain figure at all.
389 p99.insert(
390 "dequeue_batch".to_string(),
391 single(|st, i| {
392 st.time(|| black_box(q.try_dequeue_batch(&mut buf)));
393 for j in 0..BATCH {
394 q.push((i + j) as u64);
395 }
396 }),
397 );
398 p99.insert(
399 "enqueue".to_string(),
400 single(|st, i| {
401 st.time(|| q.push(i as u64));
402 let _ = q.try_dequeue_batch(&mut buf[..1]);
403 }),
404 );
405 // The producer mirror: BATCH items published behind one head swap. The
406 // drain that puts the queue back is outside the timed region for the
407 // same reason the refill is above.
408 p99.insert(
409 "enqueue_batch".to_string(),
410 single(|st, i| {
411 let base = i as u64;
412 st.time(|| black_box(q.push_batch(base..base + BATCH as u64)));
413 let _ = q.try_dequeue_batch(&mut buf);
414 }),
415 );
416 manifest.set_feature("batch", cat, &p99, &reason);
417 }
418
419 // ---------- metrics: relaxed atomic counters around each op ----------
420 #[cfg(feature = "metrics")]
421 {
422 use subms_mpsc_queue::MetricsMpscQueue;
423 fn filled_metrics(n: usize) -> MetricsMpscQueue<u64> {
424 let q = MetricsMpscQueue::new();
425 for i in 0..n {
426 q.push(i as u64);
427 }
428 q
429 }
430 let sw = sweep("metrics/push+pop", |n| {
431 let mut q = filled_metrics(n);
432 batched(ITEMS_PER_SAMPLE, |i| {
433 q.push(i as u64);
434 black_box(q.try_pop());
435 })
436 });
437 let (cat, reason) = classify_feature(&sw, Some(base_p50), None);
438
439 let mut q = filled_metrics(CANON);
440 let mut p99 = BTreeMap::new();
441 p99.insert(
442 "enqueue".to_string(),
443 single(|st, i| {
444 st.time(|| q.push(i as u64));
445 black_box(q.try_pop());
446 }),
447 );
448 p99.insert(
449 "dequeue".to_string(),
450 single(|st, i| {
451 q.push(i as u64);
452 st.time(|| black_box(q.try_pop()));
453 }),
454 );
455 p99.insert(
456 "snapshot".to_string(),
457 single(|st, _| {
458 st.time(|| black_box(q.snapshot()));
459 }),
460 );
461 manifest.set_feature("metrics", cat, &p99, &reason);
462 }
463
464 // ---------- affinity: pin the calling thread, once, at startup ----------
465 // Runs LAST because measuring it pins THIS process to core 0, and every
466 // number taken afterwards would be a number taken on one core.
467 #[cfg(feature = "affinity")]
468 {
469 use subms_mpsc_queue::set_affinity;
470 // Swept over the same axis to show what it is: a call that touches no
471 // queue state and cannot move with queue size. PINNED auxiliary rather
472 // than left to the base-delta test, which would see a syscall costing
473 // more than an enqueue and call it hot-path. It is not on the hot path at
474 // any price - `set_affinity` is called once per thread at startup and
475 // appears in neither `push` nor `try_pop`. The two ports are not even
476 // measuring the same thing: Rust issues a real `SetThreadAffinityMask` /
477 // `sched_setaffinity`, while the Java sibling validates its argument and
478 // returns UNSUPPORTED because the stock JDK has no pinning API. The
479 // per-call figure, not the sample, is the interpretable one and it is in
480 // `p99ByStage`.
481 let sw = sweep("affinity/set_affinity", |_| {
482 batched(ITEMS_PER_SAMPLE, |_| {
483 let _ = set_affinity(&[0]);
484 })
485 });
486 let (cat, reason) = classify_feature(
487 &sw,
488 Some(base_p50),
489 Some(subms::SubMsFeatureCategory::Auxiliary),
490 );
491
492 let mut p99 = BTreeMap::new();
493 p99.insert(
494 "set_affinity".to_string(),
495 single(|st, _| {
496 st.time(|| {
497 let _ = set_affinity(&[0]);
498 });
499 }),
500 );
501 manifest.set_feature("affinity", cat, &p99, &reason);
502
503 let cores: Vec<usize> = (0..std::thread::available_parallelism()
504 .map_or(1, std::num::NonZeroUsize::get))
505 .collect();
506 let _ = set_affinity(&cores);
507 }
508
509 std::fs::create_dir_all(path.parent().unwrap())?;
510 std::fs::write(&path, manifest.to_json())?;
511 io::stdout().write_all(manifest.to_json().as_bytes())?;
512 Ok(())
513}