SPB Git

Repository Public

engine_bench.rs 6.4 KB 154 lines rust

1//! ORIX Sonata2//! File: crates/sonata-render/examples/engine_bench.rs3//! Description: Engine benchmark: real-time factor and callback-time percentiles against the4//! number of sounding voices, with the shipped instruments and effects. Single thread.5//! Run: cargo run --release -p sonata-render --example engine_bench [seconds]6//!7//! Author: Simon-Pierre Boucher8//! Contact: contact@spboucher.ai910use sonata_ir::*;11use sonata_runtime::testing::{basic_graph, test_effect, test_note, test_track};12use sonata_runtime::{engine, EngineConfig, Limits, NoAssets, PreparedProgram, RegistryFactory};1314const SR: u32 = 48_000;1516/// `voices` simultaneous sustained notes of `model`, 32 per track, re-struck every second.17fn voices_program(model: &str, voices: usize, seconds: f64, effects: bool) -> Program {18    let mut p = Program::empty("bench");19    p.master.peak_limit_db = Some(-1.0);20    let per_track = 32;21    let tracks = voices.div_ceil(per_track);22    for t in 0..tracks {23        let n = per_track.min(voices - t * per_track);24        let mut notes = Vec::new();25        let mut k = 0u32;26        let mut start = 0.0;27        while start < seconds {28            for v in 0..n {29                notes.push(test_note(t as u32, k, start, start + 0.98, 36.0 + ((v * 7 + t * 5) % 60) as f64, 0.5));30                k += 1;31            }32            start += 1.0;33        }34        let mut tr = test_track(t as u32, model, notes);35        tr.gain_db = -20.0 - 10.0 * (voices as f64).log10();36        tr.pan = if tracks > 1 { t as f64 / (tracks - 1) as f64 * 2.0 - 1.0 } else { 0.0 };37        if effects {38            tr.effects.push(test_effect("eq", 1.0, &[("low_cut", 60.0), ("mid2_gain", 2.0)]));39            tr.effects.push(test_effect("compressor", 1.0, &[]));40            tr.sends.push(Send { bus: 0, gain_db: -12.0, pre_fader: false });41        }42        p.tracks.push(tr);43    }44    if effects {45        p.buses.push(Bus {46            id: 0,47            name: "reverb".into(),48            gain_db: 0.0,49            pan: 0.0,50            mute: false,51            effects: vec![test_effect("reverb", 1.0, &[])],52            sends: vec![],53            output: Output::Master,54            automation: vec![],55            span: Span::default(),56        });57    }58    p.refresh_stats();59    p60}6162struct Row {63    label: String,64    voices: u32,65    block: usize,66    rtf: f64,67    load_pct: f64,68    t: sonata_runtime::TimingSnapshot,69    budget_us: f64,70}7172fn measure(label: &str, program: &Program, block: usize, seconds: f64, max_voices: usize) -> Result<Row, String> {73    let graph = basic_graph(program, SR, &RegistryFactory, 240)?;74    let limits = Limits { max_voices, ..Limits::default() };75    let prepared = PreparedProgram::prepare(program, &graph, SR, block, &NoAssets, &limits)?;76    let (ctl, mut proc_) = engine(EngineConfig::realtime(SR));77    ctl.load(prepared).map_err(|_| "load refused".to_string())?;78    ctl.play();79    let (mut l, mut r) = (vec![0.0f32; block], vec![0.0f32; block]);80    // Warm up one second (caches, first note attacks), then measure.81    for _ in 0..(SR as usize / block) {82        proc_.process(&mut l, &mut r);83    }84    ctl.shared().reset_timing();85    let blocks = (seconds * SR as f64 / block as f64) as usize;86    let mut peak_voices = 0;87    let mut peak = 0.0f32;88    let started = std::time::Instant::now();89    for _ in 0..blocks {90        proc_.process(&mut l, &mut r);91        peak_voices = peak_voices.max(ctl.shared().active_voices());92        peak = l.iter().chain(r.iter()).fold(peak, |a, b| a.max(b.abs()));93    }94    let elapsed = started.elapsed().as_secs_f64();95    if peak < 1e-4 {96        return Err("the configuration produced no sound".into());97    }98    let audio = blocks as f64 * block as f64 / SR as f64;99    let t = ctl.shared().timing();100    Ok(Row {101        label: label.to_string(),102        voices: peak_voices,103        block,104        rtf: audio / elapsed,105        load_pct: 100.0 * elapsed / audio,106        t,107        budget_us: block as f64 / SR as f64 * 1e6,108    })109}110111fn main() {112    let seconds: f64 = std::env::args().nth(1).and_then(|s| s.parse().ok()).unwrap_or(10.0);113    println!(114        "ORIX Sonata engine benchmark: {SR} Hz, {seconds} s per row after 1 s warm-up, single thread, build: {}",115        if cfg!(debug_assertions) { "DEBUG (not representative)" } else { "release" }116    );117    println!("load = processing time / audio time; a callback misses its deadline when it takes longer than its block.");118    println!();119    println!(120        "{:<34} {:>6} {:>6} {:>9} {:>7} {:>8} {:>8} {:>8} {:>8} {:>8} {:>7}",121        "configuration", "voices*", "block", "x realtime", "load %", "p50 us", "p95 us", "p99 us", "p99.9 us", "max us", "missed"122    );123    let mut rows = Vec::new();124    let mut cases: Vec<(String, Program, usize)> = Vec::new();125    for model in ["synth", "piano", "plucked_string"] {126        for voices in [1usize, 16, 64, 256, 1024] {127            cases.push((format!("{model} x{voices}"), voices_program(model, voices, seconds + 2.0, false), 32));128        }129    }130    for voices in [16usize, 64, 256] {131        cases.push((format!("synth x{voices} + eq, comp, reverb"), voices_program("synth", voices, seconds + 2.0, true), 32));132    }133    for (label, program, max_voices) in &cases {134        for block in [128usize, 256] {135            match measure(label, program, block, seconds, *max_voices) {136                Ok(r) => {137                    println!(138                        "{:<34} {:>6} {:>6} {:>9.1} {:>7.2} {:>8.0} {:>8.0} {:>8.0} {:>8.0} {:>8.0} {:>7}",139                        r.label, r.voices, r.block, r.rtf, r.load_pct, r.t.p50_us, r.t.p95_us, r.t.p99_us, r.t.p999_us, r.t.max_us, r.t.missed_deadlines140                    );141                    rows.push(r);142                }143                Err(e) => println!("{label:<34} {:>6} {block:>6} NOT MEASURED: {e}", "-"),144            }145        }146    }147    println!();148    let ok = rows.iter().filter(|r| r.t.missed_deadlines == 0 && r.t.max_us < r.budget_us).count();149    println!("{ok} of {} rows had no callback longer than its block ({} us at 128 frames, {} us at 256).", rows.len(), 128_000_000 / SR, 256_000_000 / SR);150    println!("Percentiles are upper bounds of 5 us histogram buckets; values above 10000 us are reported as the maximum.");151    println!("* voices = largest number of simultaneously active voices observed (release tails included; 32 preallocated per track).");152    println!("This measures the engine alone, driven in a loop on one core: no audio device, no UI, no other load.");153}154
Files main
Menu

Theme