o192 0.2.2

ORION-192: ordered, resilient, independent, URL-safe 192-bit IDs for distributed systems.
Documentation
//! Rust benchmark for the ORION-192 generator.
//!
//! Usage:
//!
//! ```text
//! cargo run --release --example bench
//! N=5000000 cargo run --release --example bench
//! ```
//!
//! Reports JSON to stdout so the output is machine-readable.

use std::env;
use std::hint::black_box;
use std::time::Instant;

use o192::{decode_sortable64, encode_sortable64, parse, OrionIdGenerator};

fn time(label: &str, n: u64, mut body: impl FnMut()) -> (String, f64, u64) {
    // Warm up.
    for _ in 0..1_000 {
        body();
    }
    let start = Instant::now();
    for _ in 0..n {
        body();
    }
    let seconds = start.elapsed().as_secs_f64();
    let ops = if seconds > 0.0 {
        (n as f64 / seconds) as u64
    } else {
        0
    };
    (label.to_string(), seconds, ops)
}

fn main() {
    let n: u64 = env::var("N")
        .ok()
        .and_then(|v| v.parse().ok())
        .unwrap_or(1_000_000);

    let mut gen = OrionIdGenerator::new();
    let sample_id = gen.next().expect("generate sample");
    let sample_bytes = decode_sortable64(&sample_id).unwrap();

    let mut results: Vec<(String, f64, u64)> = Vec::new();

    results.push(time("generate.next", n, || {
        black_box(gen.next().unwrap());
    }));
    results.push(time("generate.next_bytes", n, || {
        black_box(gen.next_bytes().unwrap());
    }));
    results.push(time("encode", n, || {
        black_box(encode_sortable64(&sample_bytes).unwrap());
    }));
    results.push(time("decode", n, || {
        black_box(decode_sortable64(&sample_id).unwrap());
    }));
    results.push(time("parse", n, || {
        black_box(parse(&sample_id, 0).unwrap());
    }));

    println!("{{");
    println!("  \"n\": {n},");
    println!("  \"results\": [");
    for (i, (name, seconds, ops)) in results.iter().enumerate() {
        let comma = if i + 1 < results.len() { "," } else { "" };
        println!(
            "    {{ \"name\": \"{name}\", \"n\": {n}, \"seconds\": {seconds:.3}, \"opsPerSecond\": {ops} }}{comma}"
        );
    }
    println!("  ]");
    println!("}}");
}