SPB Git

Repository Public Apache-2.0

pqc.rs 10.9 KB 348 lines rust

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : SPB Quantum Crypto7// File             : crates/spb-pqc-core/benches/pqc.rs8// Module           : Crates9// Repository       : https://git.spboucher.ai/spb-quantum-crypto10// Project Website  : https://pqce.spboucher.ai11// Created          : 2026-12-0312// Last Modified    : 2026-12-0313//14// Author           : Simon-Pierre Boucher15// Position         : Professor of Finance16// Institution      : Université du Québec en Outaouais (UQO)17// Organization     : SP Boucher18// Website          : https://spboucher.ai19// Git              : https://git.spboucher.ai20//21// Preferred Contact: contact@spboucher.ai22// Development      : dev@spboucher.ai23// Support          : support@spboucher.ai24// Security/Admin   : admin@spboucher.ai25//26// Copyright (c) 202627// Simon-Pierre Boucher28// All rights reserved where applicable. This file is governed by the29// applicable project license, copyright notices and relevant law.30// Existing third-party rights and notices remain unaffected.31//32// License          : Apache-2.033//34// Do not embed credentials, private keys, access tokens,35// certificates or confidential personal information.36//37// =============================================================================38// END OF SP BOUCHER SOURCE HEADER39// =============================================================================4041//! `cargo bench` — wall-clock benchmarks of every public operation.42//!43//! Self-contained (no benchmarking framework): each operation is sampled44//! individually with a monotonic clock, after a warm-up, until a time budget or45//! a sample cap is reached. Reported: min, mean, p50, p95, p99 and the sample46//! count. Raw results are written as JSON and CSV under `benchmarks/results/`47//! together with the machine, OS, compiler and build flags.48//!49//! Environment: `SPB_BENCH_BUDGET_MS` (time budget per operation, default 1500),50//! `SPB_BENCH_MAX_SAMPLES` (default 2000), `SPB_BENCH_OUT` (output directory).51//!52//! Numbers are only meaningful for the machine and build recorded with them.5354use spb_pqc_core::hash::{self, HashAlg};55use spb_pqc_core::kem::{self, KemAlg};56use spb_pqc_core::signature::{self, SigAlg, SignOptions};57use std::fmt::Write as _;58use std::hint::black_box;59use std::process::Command;60use std::time::{Duration, Instant};6162struct Row {63    group: &'static str,64    algorithm: String,65    operation: &'static str,66    samples: usize,67    min: u64,68    mean: u64,69    p50: u64,70    p95: u64,71    p99: u64,72    /// Bytes processed per sample (hash throughput), 0 otherwise.73    bytes: usize,74}7576fn env_num(name: &str, default: u64) -> u64 {77    std::env::var(name)78        .ok()79        .and_then(|v| v.parse().ok())80        .unwrap_or(default)81}8283/// Samples `op` (setup excluded) and returns nanosecond statistics.84fn sample<S, T>(mut setup: impl FnMut() -> S, mut op: impl FnMut(S) -> T) -> (usize, [u64; 5]) {85    let budget = Duration::from_millis(env_num("SPB_BENCH_BUDGET_MS", 1500));86    let max = env_num("SPB_BENCH_MAX_SAMPLES", 2000) as usize;87    // warm-up: one run, plus more while it is cheap88    let warm = Instant::now();89    let mut warm_runs = 0;90    while warm_runs < 1 || (warm.elapsed() < budget / 10 && warm_runs < 50) {91        black_box(op(setup()));92        warm_runs += 1;93    }94    let mut ns = Vec::with_capacity(max.min(4096));95    let start = Instant::now();96    while ns.len() < 5 || (start.elapsed() < budget && ns.len() < max) {97        let input = setup();98        let t = Instant::now();99        let out = op(input);100        ns.push(t.elapsed().as_nanos() as u64);101        black_box(out);102    }103    ns.sort_unstable();104    let pct = |p: f64| ns[(((ns.len() - 1) as f64) * p).round() as usize];105    let mean = (ns.iter().map(|&v| v as u128).sum::<u128>() / ns.len() as u128) as u64;106    (ns.len(), [ns[0], mean, pct(0.50), pct(0.95), pct(0.99)])107}108109fn push(110    rows: &mut Vec<Row>,111    group: &'static str,112    alg: &str,113    operation: &'static str,114    bytes: usize,115    r: (usize, [u64; 5]),116) {117    let (samples, [min, mean, p50, p95, p99]) = r;118    println!(119        "{group:<9} {alg:<20} {operation:<10} n={samples:<5} p50 {:>12}  p95 {:>12}  p99 {:>12}{}",120        fmt_ns(p50),121        fmt_ns(p95),122        fmt_ns(p99),123        if bytes > 0 {124            format!(125                "  {:>8.1} MiB/s",126                bytes as f64 / (1 << 20) as f64 / (p50 as f64 / 1e9)127            )128        } else {129            String::new()130        }131    );132    rows.push(Row {133        group,134        algorithm: alg.to_string(),135        operation,136        samples,137        min,138        mean,139        p50,140        p95,141        p99,142        bytes,143    });144}145146fn fmt_ns(ns: u64) -> String {147    if ns >= 1_000_000_000 {148        format!("{:.3} s", ns as f64 / 1e9)149    } else if ns >= 1_000_000 {150        format!("{:.3} ms", ns as f64 / 1e6)151    } else {152        format!("{:.2} µs", ns as f64 / 1e3)153    }154}155156fn cmd(program: &str, args: &[&str]) -> String {157    Command::new(program)158        .args(args)159        .output()160        .ok()161        .filter(|o| o.status.success())162        .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string())163        .unwrap_or_else(|| "unknown".into())164}165166fn cpu_model() -> String {167    if cfg!(target_os = "macos") {168        cmd("sysctl", &["-n", "machdep.cpu.brand_string"])169    } else {170        std::fs::read_to_string("/proc/cpuinfo")171            .ok()172            .and_then(|s| {173                s.lines()174                    .find(|l| l.starts_with("model name"))175                    .and_then(|l| l.split(':').nth(1))176                    .map(|v| v.trim().to_string())177            })178            .unwrap_or_else(|| "unknown".into())179    }180}181182fn json_escape(s: &str) -> String {183    s.replace('\\', "\\\\").replace('"', "\\\"")184}185186fn main() {187    let mut rows = Vec::new();188    println!(189        "SPB Quantum Crypto {} — benchmarks [{}]",190        spb_pqc_core::VERSION,191        spb_pqc_core::SECURITY_STATUS192    );193194    for alg in KemAlg::ALL {195        let name = alg.name();196        push(197            &mut rows,198            "kem",199            name,200            "keygen",201            0,202            sample(|| (), |_| kem::generate_keypair(alg).unwrap()),203        );204        let (pk, sk) = kem::generate_keypair(alg).unwrap();205        push(206            &mut rows,207            "kem",208            name,209            "encaps",210            0,211            sample(|| (), |_| kem::encapsulate(&pk).unwrap()),212        );213        let enc = kem::encapsulate(&pk).unwrap();214        push(215            &mut rows,216            "kem",217            name,218            "decaps",219            0,220            sample(|| (), |_| kem::decapsulate(&sk, &enc.ciphertext).unwrap()),221        );222    }223224    let msg = [0x5Au8; 256];225    for alg in SigAlg::ALL {226        let name = alg.name();227        push(228            &mut rows,229            "signature",230            name,231            "keygen",232            0,233            sample(|| (), |_| signature::generate_keypair(alg).unwrap()),234        );235        let (pk, sk) = signature::generate_keypair(alg).unwrap();236        let opts = SignOptions::default();237        push(238            &mut rows,239            "signature",240            name,241            "sign",242            0,243            sample(|| (), |_| signature::sign_with(&sk, &msg, &opts).unwrap()),244        );245        let sig = signature::sign_with(&sk, &msg, &opts).unwrap();246        push(247            &mut rows,248            "signature",249            name,250            "verify",251            0,252            sample(253                || (),254                |_| signature::verify_with(&pk, &msg, &sig, &opts).unwrap(),255            ),256        );257    }258259    let data = vec![0xA7u8; 1 << 20];260    for alg in [261        HashAlg::Sha256,262        HashAlg::Sha512,263        HashAlg::Sha3_256,264        HashAlg::Sha3_512,265    ] {266        push(267            &mut rows,268            "hash",269            alg.name(),270            "1MiB",271            data.len(),272            sample(|| (), |_| hash::digest(alg, &data)),273        );274    }275    for alg in [HashAlg::Shake128, HashAlg::Shake256] {276        push(277            &mut rows,278            "hash",279            alg.name(),280            "1MiB",281            data.len(),282            sample(|| (), |_| hash::xof(alg, &data, 32).unwrap()),283        );284    }285286    // ---- raw results ----287    let stamp = cmd("date", &["-u", "+%Y%m%dT%H%M%SZ"]);288    let os = cmd("uname", &["-srm"]);289    let rustc = cmd("rustc", &["-V"]);290    let cpu = cpu_model();291    let target = format!("{}-{}", std::env::consts::ARCH, std::env::consts::OS);292    let out_dir = std::env::var("SPB_BENCH_OUT").unwrap_or_else(|_| {293        concat!(env!("CARGO_MANIFEST_DIR"), "/../../benchmarks/results").to_string()294    });295    let _ = std::fs::create_dir_all(&out_dir);296297    let mut json = String::new();298    let _ = write!(299        json,300        "{{\"library\":\"spb-quantum-crypto\",\"version\":\"{}\",\"securityStatus\":\"{}\",\"date\":\"{}\",\"target\":\"{}\",\"os\":\"{}\",\"cpu\":\"{}\",\"logicalCpus\":{},\"compiler\":\"{}\",\"profile\":\"bench: opt-level=3, lto=fat, codegen-units=1, default target-cpu\",\"clock\":\"std::time::Instant, one operation per sample, single thread\",\"budgetMs\":{},\"maxSamples\":{},\"unit\":\"ns\",\"results\":[",301        spb_pqc_core::VERSION,302        spb_pqc_core::SECURITY_STATUS,303        stamp,304        target,305        json_escape(&os),306        json_escape(&cpu),307        std::thread::available_parallelism().map(|n| n.get()).unwrap_or(0),308        json_escape(&rustc),309        env_num("SPB_BENCH_BUDGET_MS", 1500),310        env_num("SPB_BENCH_MAX_SAMPLES", 2000),311    );312    let mut csv = String::from(313        "group,algorithm,operation,samples,min_ns,mean_ns,p50_ns,p95_ns,p99_ns,bytes_per_sample\n",314    );315    for (i, r) in rows.iter().enumerate() {316        if i > 0 {317            json.push(',');318        }319        let _ = write!(320            json,321            "{{\"group\":\"{}\",\"algorithm\":\"{}\",\"operation\":\"{}\",\"samples\":{},\"min\":{},\"mean\":{},\"p50\":{},\"p95\":{},\"p99\":{},\"bytes\":{}}}",322            r.group, r.algorithm, r.operation, r.samples, r.min, r.mean, r.p50, r.p95, r.p99, r.bytes323        );324        let _ = writeln!(325            csv,326            "{},{},{},{},{},{},{},{},{},{}",327            r.group,328            r.algorithm,329            r.operation,330            r.samples,331            r.min,332            r.mean,333            r.p50,334            r.p95,335            r.p99,336            r.bytes337        );338    }339    json.push_str("]}\n");340    let base = format!("{out_dir}/{target}-{stamp}");341    match std::fs::write(format!("{base}.json"), &json)342        .and_then(|_| std::fs::write(format!("{base}.csv"), &csv))343    {344        Ok(()) => println!("raw results: {base}.json and .csv"),345        Err(e) => eprintln!("could not write results under {out_dir}: {e}"),346    }347}348
Files main
Menu

Theme