Skip to content
Myr

main.rs

This file

Path

src/main.rs

225 lines · 7.2 KiB · Rust

Last changed by

Pass `Copy`able enums by valuephilippbefore adoption16210a1

History of this file

Take it

1use std::cmp;2use std::env;3use std::error::Error;4use std::io;5use std::ops::Range;67use atty::Stream;8use clap::ArgMatches;9use colored::*;1011mod hyperfine;1213use crate::hyperfine::app::get_arg_matches;14use crate::hyperfine::benchmark::{mean_shell_spawning_time, run_benchmark};15use crate::hyperfine::error::{OptionsError, ParameterScanError};16use crate::hyperfine::export::{ExportManager, ExportType};17use crate::hyperfine::internal::write_benchmark_comparison;18use crate::hyperfine::types::{19    BenchmarkResult, CmdFailureAction, Command, HyperfineOptions, OutputStyleOption,20};21use crate::hyperfine::units::Unit;2223/// Print error message to stderr and terminate24pub fn error(message: &str) -> ! {25    eprintln!("{} {}", "Error:".red(), message);26    std::process::exit(1);27}2829/// Runs the benchmark for the given commands30fn run(31    commands: &[Command<'_>],32    options: &HyperfineOptions,33) -> io::Result<Vec<BenchmarkResult>> {34    let shell_spawning_time =35        mean_shell_spawning_time(&options.shell, options.output_style, options.show_output)?;3637    let mut timing_results = vec![];3839    // Run the benchmarks40    for (num, cmd) in commands.iter().enumerate() {41        timing_results.push(run_benchmark(num, cmd, shell_spawning_time, options)?);42    }4344    Ok(timing_results)45}4647/// A function to read the `--parameter-scan` arguments48fn parse_parameter_scan_args<'a>(49    mut vals: clap::Values<'a>,50) -> Result<(&'a str, Range<i32>), ParameterScanError> {51    let param_name = vals.next().unwrap();52    let param_min: i32 = vals.next().unwrap().parse()?;53    let param_max: i32 = vals.next().unwrap().parse()?;5455    const MAX_PARAMETERS: i32 = 100_000;56    if param_max - param_min > MAX_PARAMETERS {57        return Err(ParameterScanError::TooLarge);58    }5960    if param_max < param_min {61        return Err(ParameterScanError::EmptyRange);62    }6364    Ok((param_name, param_min..(param_max + 1)))65}6667fn main() {68    let matches = get_arg_matches(env::args_os());69    let options = build_hyperfine_options(&matches);70    let export_manager = build_export_manager(&matches);71    let commands = build_commands(&matches);7273    let res = match options {74        Ok(ref opts) => run(&commands, &opts),75        Err(ref e) => error(e.description()),76    };7778    match res {79        Ok(timing_results) => {80            write_benchmark_comparison(&timing_results);81            let ans = export_manager.write_results(timing_results, options.unwrap().time_unit);82            if let Err(e) = ans {83                error(&format!(84                    "The following error occurred while exporting: {}",85                    e.description()86                ));87            }88        }89        Err(e) => error(e.description()),90    }91}9293/// Build the HyperfineOptions that correspond to the given ArgMatches94fn build_hyperfine_options(matches: &ArgMatches<'_>) -> Result<HyperfineOptions, OptionsError> {95    let mut options = HyperfineOptions::default();96    let param_to_u64 = |param| matches.value_of(param).and_then(|n| u64::from_str_radix(n, 10).ok());9798    options.warmup_count = param_to_u64("warmup")99        .unwrap_or(options.warmup_count);100101    let mut min_runs = param_to_u64("min-runs");102    let mut max_runs = param_to_u64("max-runs");103104    if let Some(runs) = param_to_u64("runs") {105        min_runs = Some(runs);106        max_runs = Some(runs);107    }108109    match (min_runs, max_runs) {110        (Some(min), _) if min < 2 => {111            // We need at least two runs to compute a variance.112            return Err(OptionsError::RunsBelowTwo);113        }114        (Some(min), None) => {115            options.runs.min = min;116        }117        (_, Some(max)) if max < 2 => {118            // We need at least two runs to compute a variance.119            return Err(OptionsError::RunsBelowTwo);120        }121        (None, Some(max)) => {122            // Since the minimum was not explicit we lower it if max is below the default min.123            options.runs.min = cmp::min(options.runs.min, max);124            options.runs.max = Some(max);125        }126        (Some(min), Some(max)) if min > max => {127            return Err(OptionsError::EmptyRunsRange);128        }129        (Some(min), Some(max)) => {130            options.runs.min = min;131            options.runs.max = Some(max);132        }133        (None, None) => {}134    };135136    options.preparation_command = matches.value_of("prepare").map(String::from);137138    options.cleanup_command = matches.value_of("cleanup").map(String::from);139140    options.show_output = matches.is_present("show-output");141142    options.output_style = match matches.value_of("style") {143        Some("full") => OutputStyleOption::Full,144        Some("basic") => OutputStyleOption::Basic,145        Some("nocolor") => OutputStyleOption::NoColor,146        Some("color") => OutputStyleOption::Color,147        _ => {148            if !options.show_output && atty::is(Stream::Stdout) {149                OutputStyleOption::Full150            } else {151                OutputStyleOption::Basic152            }153        }154    };155156    // We default Windows to NoColor if full had been specified.157    if cfg!(windows) && options.output_style == OutputStyleOption::Full {158        options.output_style = OutputStyleOption::NoColor;159    }160161    match options.output_style {162        OutputStyleOption::Basic | OutputStyleOption::NoColor => {163            colored::control::set_override(false)164        }165        _ => {}166    };167168    options.shell = matches169        .value_of("shell")170        .unwrap_or(&options.shell)171        .to_string();172173    if matches.is_present("ignore-failure") {174        options.failure_action = CmdFailureAction::Ignore;175    }176177    options.time_unit = match matches.value_of("time-unit") {178        Some("millisecond") => Some(Unit::MilliSecond),179        Some("second") => Some(Unit::Second),180        _ => None,181    };182183    Ok(options)184}185186/// Build the ExportManager that will export the results specified187/// in the given ArgMatches188fn build_export_manager(matches: &ArgMatches<'_>) -> ExportManager {189    let mut export_manager = ExportManager::new();190    {191        let mut add_exporter = |flag, exporttype| {192            if let Some(filename) = matches.value_of(flag) {193                export_manager.add_exporter(exporttype, filename);194            }195        };196        add_exporter("export-asciidoc", ExportType::Asciidoc);197        add_exporter("export-json", ExportType::Json);198        add_exporter("export-csv", ExportType::Csv);199        add_exporter("export-markdown", ExportType::Markdown);200    }201    export_manager202}203204/// Build the commands to benchmark205fn build_commands<'a>(matches: &'a ArgMatches<'_>) -> Vec<Command<'a>> {206    let command_strings = matches.values_of("command").unwrap();207208    if let Some(args) = matches.values_of("parameter-scan") {209        match parse_parameter_scan_args(args) {210            Ok((param_name, param_range)) => {211                let mut commands = vec![];212                let command_strings = command_strings.collect::<Vec<&str>>();213                for value in param_range.start..param_range.end {214                    for cmd in &command_strings {215                        commands.push(Command::new_parametrized(cmd, param_name, value));216                    }217                }218                commands219            }220            Err(e) => error(e.description()),221        }222    } else {223        command_strings.map(Command::new).collect()224    }225}