Skip to main content

aprender_zram_cli/commands/
benchmark.rs

1//! Benchmark command for compression performance testing.
2//!
3//! This is a pure shim that delegates to `trueno_zram_core::benchmark`.
4
5use clap::Args;
6use trueno_zram_core::benchmark::{
7    generate_test_pages, parse_algorithm, run_benchmark, DataPattern,
8};
9
10/// Arguments for benchmark command.
11#[derive(Debug, Args)]
12pub struct BenchmarkArgs {
13    /// Number of pages to compress.
14    ///
15    /// Short form is `-n`, not `-p`: `pattern` below explicitly claims `-p`,
16    /// and a derived `short` here claimed it too. clap catches that in a
17    /// `debug_assert`, so EVERY `trueno-zram benchmark` invocation -- including
18    /// `--help` -- panicked before reaching this code. Nothing ever ran the
19    /// command, so nothing noticed.
20    #[arg(short = 'n', long, default_value = "10000")]
21    pub pages: usize,
22
23    /// Algorithm to benchmark (lz4, zstd, all).
24    #[arg(short, long, default_value = "all")]
25    pub algorithm: String,
26
27    /// Data pattern (zero, random, text, mixed).
28    // Long-only: `-p` is taken by `pages` above. See the note in
29    // aprender-train-lora's `method` -- same defect, same crate family.
30    #[arg(long, default_value = "mixed")]
31    pub pattern: String,
32}
33
34/// Run compression benchmarks.
35///
36/// # Errors
37/// Returns an error if the data pattern or algorithm name is not recognised,
38/// or if the underlying `trueno_zram_core` benchmark fails.
39pub fn benchmark(args: &BenchmarkArgs) -> Result<(), Box<dyn std::error::Error>> {
40    let pattern = DataPattern::parse(&args.pattern)
41        .ok_or_else(|| format!("Unknown pattern: {}", args.pattern))?;
42
43    let algorithms = parse_algorithm(&args.algorithm)
44        .ok_or_else(|| format!("Unknown algorithm: {}", args.algorithm))?;
45
46    println!("trueno-zram Compression Benchmark");
47    println!("==================================");
48    println!("Pages: {}", args.pages);
49    println!("Pattern: {pattern:?}");
50    println!();
51
52    // Generate test data
53    let pages = generate_test_pages(args.pages, pattern);
54
55    println!(
56        "{:<15} {:>10} {:>12} {:>12} {:>10}",
57        "Algorithm", "Backend", "Compress", "Decompress", "Ratio"
58    );
59    println!("{}", "-".repeat(60));
60
61    for algo in algorithms {
62        let result = run_benchmark(algo, &pages)?;
63
64        let compress_throughput = result.compress_throughput() / 1e9;
65        let decompress_throughput = result.decompress_throughput() / 1e9;
66
67        println!(
68            "{:<15} {:>10} {:>10.2} GB/s {:>10.2} GB/s {:>9.2}x",
69            format!("{:?}", result.algorithm),
70            format!("{:?}", result.backend),
71            compress_throughput,
72            decompress_throughput,
73            result.compression_ratio()
74        );
75    }
76
77    Ok(())
78}