main.rs
This file
Path
src/main.rs
233 lines · 7.6 KiB · Rust
Last changed by
remove deprecated Error::descriptionAndrii Radykbefore adoption9a064b7
History of this fileTake it
1use std::cmp;2use std::env;3use std::io;45use atty::Stream;6use clap::ArgMatches;7use colored::*;89mod hyperfine;1011use crate::hyperfine::app::get_arg_matches;12use crate::hyperfine::benchmark::{mean_shell_spawning_time, run_benchmark};13use crate::hyperfine::error::OptionsError;14use crate::hyperfine::export::{ExportManager, ExportType};15use crate::hyperfine::internal::{tokenize, write_benchmark_comparison};16use crate::hyperfine::parameter_range::get_parameterized_commands;17use crate::hyperfine::types::{18 BenchmarkResult, CmdFailureAction, Command, HyperfineOptions, OutputStyleOption, ParameterValue,19};20use crate::hyperfine::units::Unit;2122/// Print error message to stderr and terminate23pub fn error(message: &str) -> ! {24 eprintln!("{} {}", "Error:".red(), message);25 std::process::exit(1);26}2728/// Runs the benchmark for the given commands29fn run(commands: &[Command<'_>], options: &HyperfineOptions) -> io::Result<Vec<BenchmarkResult>> {30 let shell_spawning_time =31 mean_shell_spawning_time(&options.shell, options.output_style, options.show_output)?;3233 let mut timing_results = vec![];3435 if let Some(preparation_command) = &options.preparation_command {36 if preparation_command.len() > 1 && commands.len() != preparation_command.len() {37 error(38 "The '--prepare' option has to be provided just once or N times, where N is the \39 number of benchmark commands.",40 );41 }42 }4344 // Run the benchmarks45 for (num, cmd) in commands.iter().enumerate() {46 timing_results.push(run_benchmark(num, cmd, shell_spawning_time, options)?);47 }4849 Ok(timing_results)50}5152fn main() {53 let matches = get_arg_matches(env::args_os());54 let options = build_hyperfine_options(&matches);55 let export_manager = build_export_manager(&matches);56 let commands = build_commands(&matches);5758 let res = match options {59 Ok(ref opts) => run(&commands, &opts),60 Err(ref e) => error(&e.to_string()),61 };6263 match res {64 Ok(timing_results) => {65 let options = options.unwrap();6667 if options.output_style != OutputStyleOption::Disabled {68 write_benchmark_comparison(&timing_results);69 }7071 let ans = export_manager.write_results(timing_results, options.time_unit);72 if let Err(e) = ans {73 error(&format!(74 "The following error occurred while exporting: {}",75 e76 ));77 }78 }79 Err(e) => error(&e.to_string()),80 }81}8283/// Build the HyperfineOptions that correspond to the given ArgMatches84fn build_hyperfine_options(matches: &ArgMatches<'_>) -> Result<HyperfineOptions, OptionsError> {85 let mut options = HyperfineOptions::default();86 let param_to_u64 = |param| {87 matches88 .value_of(param)89 .and_then(|n| u64::from_str_radix(n, 10).ok())90 };9192 options.warmup_count = param_to_u64("warmup").unwrap_or(options.warmup_count);9394 let mut min_runs = param_to_u64("min-runs");95 let mut max_runs = param_to_u64("max-runs");9697 if let Some(runs) = param_to_u64("runs") {98 min_runs = Some(runs);99 max_runs = Some(runs);100 }101102 match (min_runs, max_runs) {103 (Some(min), _) if min < 2 => {104 // We need at least two runs to compute a variance.105 return Err(OptionsError::RunsBelowTwo);106 }107 (Some(min), None) => {108 options.runs.min = min;109 }110 (_, Some(max)) if max < 2 => {111 // We need at least two runs to compute a variance.112 return Err(OptionsError::RunsBelowTwo);113 }114 (None, Some(max)) => {115 // Since the minimum was not explicit we lower it if max is below the default min.116 options.runs.min = cmp::min(options.runs.min, max);117 options.runs.max = Some(max);118 }119 (Some(min), Some(max)) if min > max => {120 return Err(OptionsError::EmptyRunsRange);121 }122 (Some(min), Some(max)) => {123 options.runs.min = min;124 options.runs.max = Some(max);125 }126 (None, None) => {}127 };128129 options.preparation_command = matches130 .values_of("prepare")131 .map(|values| values.map(String::from).collect::<Vec<String>>());132133 options.cleanup_command = matches.value_of("cleanup").map(String::from);134135 options.show_output = matches.is_present("show-output");136137 options.output_style = match matches.value_of("style") {138 Some("full") => OutputStyleOption::Full,139 Some("basic") => OutputStyleOption::Basic,140 Some("nocolor") => OutputStyleOption::NoColor,141 Some("color") => OutputStyleOption::Color,142 Some("none") => OutputStyleOption::Disabled,143 _ => {144 if !options.show_output && atty::is(Stream::Stdout) {145 OutputStyleOption::Full146 } else {147 OutputStyleOption::Basic148 }149 }150 };151152 // We default Windows to NoColor if full had been specified.153 if cfg!(windows) && options.output_style == OutputStyleOption::Full {154 options.output_style = OutputStyleOption::NoColor;155 }156157 match options.output_style {158 OutputStyleOption::Basic | OutputStyleOption::NoColor => {159 colored::control::set_override(false)160 }161 _ => {}162 };163164 options.shell = matches165 .value_of("shell")166 .unwrap_or(&options.shell)167 .to_string();168169 if matches.is_present("ignore-failure") {170 options.failure_action = CmdFailureAction::Ignore;171 }172173 options.time_unit = match matches.value_of("time-unit") {174 Some("millisecond") => Some(Unit::MilliSecond),175 Some("second") => Some(Unit::Second),176 _ => None,177 };178179 Ok(options)180}181182/// Build the ExportManager that will export the results specified183/// in the given ArgMatches184fn build_export_manager(matches: &ArgMatches<'_>) -> ExportManager {185 let mut export_manager = ExportManager::new();186 {187 let mut add_exporter = |flag, exporttype| {188 if let Some(filename) = matches.value_of(flag) {189 export_manager.add_exporter(exporttype, filename);190 }191 };192 add_exporter("export-asciidoc", ExportType::Asciidoc);193 add_exporter("export-json", ExportType::Json);194 add_exporter("export-csv", ExportType::Csv);195 add_exporter("export-markdown", ExportType::Markdown);196 }197 export_manager198}199200/// Build the commands to benchmark201fn build_commands<'a>(matches: &'a ArgMatches<'_>) -> Vec<Command<'a>> {202 let command_strings = matches.values_of("command").unwrap();203204 if let Some(args) = matches.values_of("parameter-scan") {205 let step_size = matches.value_of("parameter-step-size");206 match get_parameterized_commands(command_strings, args, step_size) {207 Ok(commands) => commands,208 Err(e) => error(&e.to_string()),209 }210 } else if let Some(mut args) = matches.values_of("parameter-list") {211 let param_name = args.next().unwrap();212 let param_list_str = args.next().unwrap();213214 let param_list = tokenize(param_list_str);215 let command_list = command_strings.collect::<Vec<&str>>();216217 let mut commands = Vec::with_capacity(param_list.len() * command_list.len());218219 for value in param_list {220 for cmd in &command_list {221 commands.push(Command::new_parametrized(222 cmd,223 param_name,224 ParameterValue::Text(value.clone()),225 ));226 }227 }228229 commands230 } else {231 command_strings.map(Command::new).collect()232 }233}