Skip to main content

ellip_dev_utils/
benchmark.rs

1/*
2 * Ellip is licensed under The 3-Clause BSD, see LICENSE.
3 * Copyright 2025 Sira Pornsiriprasert <code@psira.me>
4 */
5
6use std::path::{Path, PathBuf};
7use std::sync::LazyLock;
8
9use crate::StrErr;
10
11/// Resolves Criterion's output directory once, using the same precedence as Criterion.
12pub fn criterion_output_directory() -> &'static Path {
13    static DIRECTORY: LazyLock<PathBuf> = LazyLock::new(|| {
14        if let Some(path) = std::env::var_os("CRITERION_HOME") {
15            return PathBuf::from(path);
16        }
17        if let Some(path) = std::env::var_os("CARGO_TARGET_DIR") {
18            return PathBuf::from(path).join("criterion");
19        }
20
21        #[derive(serde::Deserialize)]
22        struct Metadata {
23            target_directory: PathBuf,
24        }
25
26        let target_directory = (|| -> Result<PathBuf, Box<dyn std::error::Error>> {
27            let output = std::process::Command::new(
28                std::env::var_os("CARGO").unwrap_or_else(|| "cargo".into()),
29            )
30            .args(["metadata", "--no-deps", "--format-version", "1"])
31            .output()?;
32            if !output.status.success() {
33                return Err(String::from_utf8_lossy(&output.stderr).into_owned().into());
34            }
35            Ok(serde_json::from_slice::<Metadata>(&output.stdout)?.target_directory)
36        })();
37
38        match target_directory {
39            Ok(path) => path.join("criterion"),
40            Err(error) => {
41                eprintln!("Cannot resolve Cargo target directory: {error}; using target/criterion");
42                PathBuf::from("target/criterion")
43            }
44        }
45    });
46    &DIRECTORY
47}
48
49/// Criterion benchmark estimates structure
50#[derive(Debug, serde::Deserialize)]
51pub struct CriterionEstimates {
52    pub mean: CriterionMean,
53}
54
55/// Criterion mean structure
56#[derive(Debug, serde::Deserialize)]
57pub struct CriterionMean {
58    pub point_estimate: f64,
59}
60
61pub fn extract_criterion_mean(path: &PathBuf) -> Result<f64, StrErr> {
62    use std::fs;
63    let content = fs::read_to_string(path).map_err(|_| "Cannot read estimates.json file")?;
64
65    let estimates: CriterionEstimates =
66        serde_json::from_str(&content).map_err(|_| "Cannot parse estimates.json file")?;
67
68    Ok(estimates.mean.point_estimate)
69}
70
71pub fn extract_criterion_means(paths: &[PathBuf]) -> Result<Vec<f64>, StrErr> {
72    paths
73        .iter()
74        .map(|path| extract_criterion_mean(path))
75        .collect()
76}
77
78#[cfg(test)]
79mod tests {
80    use super::*;
81    use std::fs;
82    use tempfile::tempdir;
83
84    #[test]
85    fn test_extract_criterion_mean() {
86        // Create a temporary directory with a mock estimates.json
87        let temp_dir = tempdir().unwrap();
88        let estimates_content = r#"{
89            "mean": {
90                "confidence_interval": {
91                    "confidence_level": 0.95,
92                    "lower_bound": 100.0,
93                    "upper_bound": 200.0
94                },
95                "point_estimate": 150.5,
96                "standard_error": 25.0
97            }
98        }"#;
99
100        let estimates_path = temp_dir.path().join("estimates.json");
101        fs::write(&estimates_path, estimates_content).unwrap();
102
103        let mean = extract_criterion_mean(&estimates_path).unwrap();
104        assert_eq!(mean, 150.5);
105    }
106
107    #[test]
108    fn test_extract_criterion_means() {
109        // Create temporary directories with mock estimates.json files
110        let temp_dir1 = tempdir().unwrap();
111        let temp_dir2 = tempdir().unwrap();
112
113        let estimates_content1 = r#"{"mean":{"point_estimate":100.0}}"#;
114        let estimates_content2 = r#"{"mean":{"point_estimate":200.0}}"#;
115
116        let paths = vec![
117            temp_dir1.path().join("estimates.json"),
118            temp_dir2.path().join("estimates.json"),
119        ];
120
121        fs::write(paths[0].clone(), estimates_content1).unwrap();
122        fs::write(paths[1].clone(), estimates_content2).unwrap();
123
124        let means = extract_criterion_means(&paths).unwrap();
125        assert_eq!(means, vec![100.0, 200.0]);
126    }
127}