Flat directory/module structure
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by David Peter · committed by David Peter · parent d31936e · Browse files · 51 files·+3148 added−3149 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
51 files+3148 added−3149 removed
- other:+3148 added−3149 removed
Provenance
- Commit
30c381f- Tree
c4e9e73- Author
David Peter <mail@david-peter.de>- Committer
David Peter <sharkdp@users.noreply.github.com>- Parent
d31936e
51 files changed+3148 added−3149 removed
added:src/export/asciidoc.rs+237 added
1+use super::Exporter;2+3+use crate::benchmark_result::BenchmarkResult;4+use crate::format::format_duration_value;5+use crate::units::Unit;6+7+use std::io::Result;8+9+#[derive(Default)]10+pub struct AsciidocExporter {}11+12+impl Exporter for AsciidocExporter {13+ fn serialize(&self, results: &[BenchmarkResult], unit: Option<Unit>) -> Result<Vec<u8>> {14+ let unit = if let Some(unit) = unit {15+ // Use the given unit for all entries.16+ unit17+ } else if let Some(first_result) = results.first() {18+ // Use the first BenchmarkResult entry to determine the unit for all entries.19+ format_duration_value(first_result.mean, None).120+ } else {21+ // Default to `Second`.22+ Unit::Second23+ };24+25+ let mut res: Vec<u8> = Vec::new();26+ res.append(&mut table_open());27+ res.append(&mut table_startend());28+ res.append(&mut table_header(unit));29+ for result in results {30+ res.push(b'\n');31+ res.append(&mut table_row(result, unit));32+ }33+ res.append(&mut table_startend());34+35+ Ok(res)36+ }37+}38+39+fn table_open() -> Vec<u8> {40+ "[cols=\"<,>,>\"]\n".bytes().collect()41+}42+43+fn table_startend() -> Vec<u8> {44+ "|===\n".bytes().collect()45+}46+47+fn table_header(unittype: Unit) -> Vec<u8> {48+ let unit_short_name = unittype.short_name();49+ format!(50+ "| Command | Mean [{unit}] | Min…Max [{unit}]\n",51+ unit = unit_short_name52+ )53+ .into_bytes()54+}55+56+fn table_row(entry: &BenchmarkResult, unit: Unit) -> Vec<u8> {57+ let form = |val| format_duration_value(val, Some(unit));58+ format!(59+ "| `{}`\n\60+ | {} ± {}\n\61+ | {}…{}\n",62+ entry.command.replace("|", "\\|"),63+ form(entry.mean).0,64+ form(entry.stddev).0,65+ form(entry.min).0,66+ form(entry.max).067+ )68+ .into_bytes()69+}70+71+/// Ensure various options for the header generate correct results72+#[test]73+fn test_asciidoc_header() {74+ let conms: Vec<u8> = "| Command | Mean [ms] | Min…Max [ms]\n".bytes().collect();75+ let cons: Vec<u8> = "| Command | Mean [s] | Min…Max [s]\n".bytes().collect();76+ let genms = table_header(Unit::MilliSecond);77+ let gens = table_header(Unit::Second);78+79+ assert_eq!(conms, genms);80+ assert_eq!(cons, gens);81+}82+83+/// Ensure each table row is generated properly84+#[test]85+fn test_asciidoc_table_row() {86+ use std::collections::BTreeMap;87+ let result = BenchmarkResult::new(88+ String::from("sleep 1"), // command89+ 0.10491992406666667, // mean90+ 0.00397851689425097, // stddev91+ 0.10491992406666667, // median92+ 0.005182013333333333, // user93+ 0.0, // system94+ 0.1003342584, // min95+ 0.10745223440000001, // max96+ vec![97+ // times98+ 0.1003342584,99+ 0.10745223440000001,100+ 0.10697327940000001,101+ ],102+ vec![Some(0), Some(0), Some(0)], // exit codes103+ BTreeMap::new(), // param104+ );105+106+ let expms = format!(107+ "| `{}`\n\108+ | {} ± {}\n\109+ | {}…{}\n",110+ result.command,111+ Unit::MilliSecond.format(result.mean),112+ Unit::MilliSecond.format(result.stddev),113+ Unit::MilliSecond.format(result.min),114+ Unit::MilliSecond.format(result.max)115+ )116+ .into_bytes();117+ let exps = format!(118+ "| `{}`\n\119+ | {} ± {}\n\120+ | {}…{}\n",121+ result.command,122+ Unit::Second.format(result.mean),123+ Unit::Second.format(result.stddev),124+ Unit::Second.format(result.min),125+ Unit::Second.format(result.max)126+ )127+ .into_bytes();128+129+ let genms = table_row(&result, Unit::MilliSecond);130+ let gens = table_row(&result, Unit::Second);131+132+ assert_eq!(expms, genms);133+ assert_eq!(exps, gens);134+}135+136+/// Ensure commands get properly escaped137+#[test]138+fn test_asciidoc_table_row_command_escape() {139+ use std::collections::BTreeMap;140+ let result = BenchmarkResult::new(141+ String::from("sleep 1|"), // command142+ 0.10491992406666667, // mean143+ 0.00397851689425097, // stddev144+ 0.10491992406666667, // median145+ 0.005182013333333333, // user146+ 0.0, // system147+ 0.1003342584, // min148+ 0.10745223440000001, // max149+ vec![150+ // times151+ 0.1003342584,152+ 0.10745223440000001,153+ 0.10697327940000001,154+ ],155+ vec![Some(0), Some(0), Some(0)], // exit codes156+ BTreeMap::new(), // param157+ );158+ let exps = format!(159+ "| `sleep 1\\|`\n\160+ | {} ± {}\n\161+ | {}…{}\n",162+ Unit::Second.format(result.mean),163+ Unit::Second.format(result.stddev),164+ Unit::Second.format(result.min),165+ Unit::Second.format(result.max)166+ )167+ .into_bytes();168+ let gens = table_row(&result, Unit::Second);169+170+ assert_eq!(exps, gens);171+}172+173+/// Integration test174+#[test]175+fn test_asciidoc() {176+ use std::collections::BTreeMap;177+ let exporter = AsciidocExporter::default();178+ // NOTE: results are fabricated, unlike above179+ let results = vec![180+ BenchmarkResult::new(181+ String::from("FOO=1 BAR=2 command | 1"),182+ 1.0,183+ 2.0,184+ 1.0,185+ 3.0,186+ 4.0,187+ 5.0,188+ 6.0,189+ vec![7.0, 8.0, 9.0],190+ vec![Some(0), Some(0), Some(0)],191+ {192+ let mut params = BTreeMap::new();193+ params.insert("foo".into(), "1".into());194+ params.insert("bar".into(), "2".into());195+ params196+ },197+ ),198+ BenchmarkResult::new(199+ String::from("FOO=1 BAR=7 command | 2"),200+ 11.0,201+ 12.0,202+ 11.0,203+ 13.0,204+ 14.0,205+ 15.0,206+ 16.0,207+ vec![17.0, 18.0, 19.0],208+ vec![Some(0), Some(0), Some(0)],209+ {210+ let mut params = BTreeMap::new();211+ params.insert("foo".into(), "1".into());212+ params.insert("bar".into(), "7".into());213+ params214+ },215+ ),216+ ];217+ // NOTE: only testing with s, s/ms is tested elsewhere218+ let exps: String = String::from(219+ "[cols=\"<,>,>\"]\n\220+ |===\n\221+ | Command | Mean [s] | Min…Max [s]\n\222+ \n\223+ | `FOO=1 BAR=2 command \\| 1`\n\224+ | 1.000 ± 2.000\n\225+ | 5.000…6.000\n\226+ \n\227+ | `FOO=1 BAR=7 command \\| 2`\n\228+ | 11.000 ± 12.000\n\229+ | 15.000…16.000\n\230+ |===\n\231+ ",232+ );233+ let gens =234+ String::from_utf8(exporter.serialize(&results, Some(Unit::Second)).unwrap()).unwrap();235+236+ assert_eq!(exps, gens);237+}added:src/export/csv.rs+107 added
1+use super::Exporter;2+3+use crate::benchmark_result::BenchmarkResult;4+use crate::units::Unit;5+6+use std::borrow::Cow;7+use std::io::{Error, ErrorKind, Result};8+9+use csv::WriterBuilder;10+11+#[derive(Default)]12+pub struct CsvExporter {}13+14+impl Exporter for CsvExporter {15+ fn serialize(&self, results: &[BenchmarkResult], _unit: Option<Unit>) -> Result<Vec<u8>> {16+ let mut writer = WriterBuilder::new().from_writer(vec![]);17+18+ {19+ let mut headers: Vec<Cow<[u8]>> = [20+ // The list of times and exit codes cannot be exported to the CSV file - omit them.21+ "command", "mean", "stddev", "median", "user", "system", "min", "max",22+ ]23+ .iter()24+ .map(|x| Cow::Borrowed(x.as_bytes()))25+ .collect();26+ if let Some(res) = results.first() {27+ for param_name in res.parameters.keys() {28+ headers.push(Cow::Owned(format!("parameter_{}", param_name).into_bytes()));29+ }30+ }31+ writer.write_record(headers)?;32+ }33+34+ for res in results {35+ let mut fields = vec![Cow::Borrowed(res.command.as_bytes())];36+ for f in &[37+ res.mean, res.stddev, res.median, res.user, res.system, res.min, res.max,38+ ] {39+ fields.push(Cow::Owned(f.to_string().into_bytes()))40+ }41+ for v in res.parameters.values() {42+ fields.push(Cow::Borrowed(v.as_bytes()))43+ }44+ writer.write_record(fields)?;45+ }46+47+ writer48+ .into_inner()49+ .map_err(|e| Error::new(ErrorKind::Other, e))50+ }51+}52+53+#[test]54+fn test_csv() {55+ use std::collections::BTreeMap;56+ let exporter = CsvExporter::default();57+58+ // NOTE: results are fabricated59+ let results = vec![60+ BenchmarkResult::new(61+ String::from("FOO=one BAR=two command | 1"),62+ 1.0,63+ 2.0,64+ 1.0,65+ 3.0,66+ 4.0,67+ 5.0,68+ 6.0,69+ vec![7.0, 8.0, 9.0],70+ vec![Some(0), Some(0), Some(0)],71+ {72+ let mut params = BTreeMap::new();73+ params.insert("foo".into(), "one".into());74+ params.insert("bar".into(), "two".into());75+ params76+ },77+ ),78+ BenchmarkResult::new(79+ String::from("FOO=one BAR=seven command | 2"),80+ 11.0,81+ 12.0,82+ 11.0,83+ 13.0,84+ 14.0,85+ 15.0,86+ 16.5,87+ vec![17.0, 18.0, 19.0],88+ vec![Some(0), Some(0), Some(0)],89+ {90+ let mut params = BTreeMap::new();91+ params.insert("foo".into(), "one".into());92+ params.insert("bar".into(), "seven".into());93+ params94+ },95+ ),96+ ];97+ let exps: String = String::from(98+ "command,mean,stddev,median,user,system,min,max,parameter_bar,parameter_foo\n\99+ FOO=one BAR=two command | 1,1,2,1,3,4,5,6,two,one\n\100+ FOO=one BAR=seven command | 2,11,12,11,13,14,15,16.5,seven,one\n\101+ ",102+ );103+ let gens =104+ String::from_utf8(exporter.serialize(&results, Some(Unit::Second)).unwrap()).unwrap();105+106+ assert_eq!(exps, gens);107+}added:src/export/json.rs+27 added
1+use super::Exporter;2+use crate::benchmark_result::BenchmarkResult;3+use crate::units::Unit;4+5+use std::io::{Error, ErrorKind, Result};6+7+use serde::*;8+use serde_json::to_vec_pretty;9+10+#[derive(Serialize, Debug)]11+struct HyperfineSummary<'a> {12+ results: &'a [BenchmarkResult],13+}14+15+#[derive(Default)]16+pub struct JsonExporter {}17+18+impl Exporter for JsonExporter {19+ fn serialize(&self, results: &[BenchmarkResult], _unit: Option<Unit>) -> Result<Vec<u8>> {20+ let mut output = to_vec_pretty(&HyperfineSummary { results });21+ for content in output.iter_mut() {22+ content.push(b'\n');23+ }24+25+ output.map_err(|e| Error::new(ErrorKind::Other, e))26+ }27+}added:src/export/markdown.rs+293 added
1+use super::Exporter;2+3+use crate::benchmark_result::BenchmarkResult;4+use crate::format::format_duration_value;5+use crate::internal::{compute_relative_speed, BenchmarkResultWithRelativeSpeed};6+use crate::units::Unit;7+8+use std::io::{Error, ErrorKind, Result};9+10+#[derive(Default)]11+pub struct MarkdownExporter {}12+13+impl Exporter for MarkdownExporter {14+ fn serialize(&self, results: &[BenchmarkResult], unit: Option<Unit>) -> Result<Vec<u8>> {15+ let unit = if let Some(unit) = unit {16+ // Use the given unit for all entries.17+ unit18+ } else if let Some(first_result) = results.first() {19+ // Use the first BenchmarkResult entry to determine the unit for all entries.20+ format_duration_value(first_result.mean, None).121+ } else {22+ // Default to `Second`.23+ Unit::Second24+ };25+26+ if let Some(annotated_results) = compute_relative_speed(results) {27+ let mut destination = start_table(unit);28+29+ for result in annotated_results {30+ add_table_row(&mut destination, &result, unit);31+ }32+33+ Ok(destination)34+ } else {35+ Err(Error::new(36+ ErrorKind::Other,37+ "Relative speed comparison is not available for Markdown export.",38+ ))39+ }40+ }41+}42+43+fn table_header(unit_short_name: String) -> String {44+ format!(45+ "| Command | Mean [{unit}] | Min [{unit}] | Max [{unit}] | Relative |\n|:---|---:|---:|---:|---:|\n",46+ unit = unit_short_name47+ )48+}49+50+fn start_table(unit: Unit) -> Vec<u8> {51+ table_header(unit.short_name()).bytes().collect()52+}53+54+fn add_table_row(dest: &mut Vec<u8>, entry: &BenchmarkResultWithRelativeSpeed, unit: Unit) {55+ let result = &entry.result;56+ let mean_str = format_duration_value(result.mean, Some(unit)).0;57+ let stddev_str = format_duration_value(result.stddev, Some(unit)).0;58+ let min_str = format_duration_value(result.min, Some(unit)).0;59+ let max_str = format_duration_value(result.max, Some(unit)).0;60+ let rel_str = format!("{:.2}", entry.relative_speed);61+ let rel_stddev_str = if entry.is_fastest {62+ "".into()63+ } else {64+ format!(" ± {:.2}", entry.relative_speed_stddev)65+ };66+67+ dest.extend(68+ format!(69+ "| `{command}` | {mean} ± {stddev} | {min} | {max} | {rel}{rel_stddev} |\n",70+ command = result.command.replace("|", "\\|"),71+ mean = mean_str,72+ stddev = stddev_str,73+ min = min_str,74+ max = max_str,75+ rel = rel_str,76+ rel_stddev = rel_stddev_str,77+ )78+ .as_bytes(),79+ );80+}81+82+/// Ensure the markdown output includes the table header and the multiple83+/// benchmark results as a table. The list of actual times is not included84+/// in the output.85+///86+/// This also demonstrates that the first entry's units (ms) are used to set87+/// the units for all entries when the time unit is not given.88+#[test]89+fn test_markdown_format_ms() {90+ use std::collections::BTreeMap;91+ let exporter = MarkdownExporter::default();92+93+ let mut timing_results = vec![];94+95+ timing_results.push(BenchmarkResult::new(96+ String::from("sleep 0.1"),97+ 0.1057, // mean98+ 0.0016, // std dev99+ 0.1057, // median100+ 0.0009, // user_mean101+ 0.0011, // system_mean102+ 0.1023, // min103+ 0.1080, // max104+ vec![0.1, 0.1, 0.1], // times105+ vec![Some(0), Some(0), Some(0)], // exit codes106+ BTreeMap::new(), // parameter107+ ));108+109+ timing_results.push(BenchmarkResult::new(110+ String::from("sleep 2"),111+ 2.0050, // mean112+ 0.0020, // std dev113+ 2.0050, // median114+ 0.0009, // user_mean115+ 0.0012, // system_mean116+ 2.0020, // min117+ 2.0080, // max118+ vec![2.0, 2.0, 2.0], // times119+ vec![Some(0), Some(0), Some(0)], // exit codes120+ BTreeMap::new(), // parameter121+ ));122+123+ let formatted = String::from_utf8(exporter.serialize(&timing_results, None).unwrap()).unwrap();124+125+ let formatted_expected = format!(126+ "{}\127+| `sleep 0.1` | 105.7 ± 1.6 | 102.3 | 108.0 | 1.00 |128+| `sleep 2` | 2005.0 ± 2.0 | 2002.0 | 2008.0 | 18.97 ± 0.29 |129+",130+ table_header("ms".to_string())131+ );132+133+ assert_eq!(formatted_expected, formatted);134+}135+136+/// This (again) demonstrates that the first entry's units (s) are used to set137+/// the units for all entries when the time unit is not given.138+#[test]139+fn test_markdown_format_s() {140+ use std::collections::BTreeMap;141+ let exporter = MarkdownExporter::default();142+143+ let mut timing_results = vec![];144+145+ timing_results.push(BenchmarkResult::new(146+ String::from("sleep 2"),147+ 2.0050, // mean148+ 0.0020, // std dev149+ 2.0050, // median150+ 0.0009, // user_mean151+ 0.0012, // system_mean152+ 2.0020, // min153+ 2.0080, // max154+ vec![2.0, 2.0, 2.0], // times155+ vec![Some(0), Some(0), Some(0)], // exit codes156+ BTreeMap::new(), // parameter157+ ));158+159+ timing_results.push(BenchmarkResult::new(160+ String::from("sleep 0.1"),161+ 0.1057, // mean162+ 0.0016, // std dev163+ 0.1057, // median164+ 0.0009, // user_mean165+ 0.0011, // system_mean166+ 0.1023, // min167+ 0.1080, // max168+ vec![0.1, 0.1, 0.1], // times169+ vec![Some(0), Some(0), Some(0)], // exit codes170+ BTreeMap::new(), // parameter171+ ));172+173+ let formatted = String::from_utf8(exporter.serialize(&timing_results, None).unwrap()).unwrap();174+175+ let formatted_expected = format!(176+ "{}\177+| `sleep 2` | 2.005 ± 0.002 | 2.002 | 2.008 | 18.97 ± 0.29 |178+| `sleep 0.1` | 0.106 ± 0.002 | 0.102 | 0.108 | 1.00 |179+",180+ table_header("s".to_string())181+ );182+183+ assert_eq!(formatted_expected, formatted);184+}185+186+/// The given time unit (s) is used to set the units for all entries.187+#[test]188+fn test_markdown_format_time_unit_s() {189+ use std::collections::BTreeMap;190+ let exporter = MarkdownExporter::default();191+192+ let mut timing_results = vec![];193+194+ timing_results.push(BenchmarkResult::new(195+ String::from("sleep 0.1"),196+ 0.1057, // mean197+ 0.0016, // std dev198+ 0.1057, // median199+ 0.0009, // user_mean200+ 0.0011, // system_mean201+ 0.1023, // min202+ 0.1080, // max203+ vec![0.1, 0.1, 0.1], // times204+ vec![Some(0), Some(0), Some(0)], // exit codes205+ BTreeMap::new(), // parameter206+ ));207+208+ timing_results.push(BenchmarkResult::new(209+ String::from("sleep 2"),210+ 2.0050, // mean211+ 0.0020, // std dev212+ 2.0050, // median213+ 0.0009, // user_mean214+ 0.0012, // system_mean215+ 2.0020, // min216+ 2.0080, // max217+ vec![2.0, 2.0, 2.0], // times218+ vec![Some(0), Some(0), Some(0)], // exit codes219+ BTreeMap::new(), // parameter220+ ));221+222+ let formatted = String::from_utf8(223+ exporter224+ .serialize(&timing_results, Some(Unit::Second))225+ .unwrap(),226+ )227+ .unwrap();228+229+ let formatted_expected = format!(230+ "{}\231+| `sleep 0.1` | 0.106 ± 0.002 | 0.102 | 0.108 | 1.00 |232+| `sleep 2` | 2.005 ± 0.002 | 2.002 | 2.008 | 18.97 ± 0.29 |233+",234+ table_header("s".to_string())235+ );236+237+ assert_eq!(formatted_expected, formatted);238+}239+240+/// This (again) demonstrates that the given time unit (ms) is used to set241+/// the units for all entries.242+#[test]243+fn test_markdown_format_time_unit_ms() {244+ use std::collections::BTreeMap;245+ let exporter = MarkdownExporter::default();246+247+ let mut timing_results = vec![];248+249+ timing_results.push(BenchmarkResult::new(250+ String::from("sleep 2"),251+ 2.0050, // mean252+ 0.0020, // std dev253+ 2.0050, // median254+ 0.0009, // user_mean255+ 0.0012, // system_mean256+ 2.0020, // min257+ 2.0080, // max258+ vec![2.0, 2.0, 2.0], // times259+ vec![Some(0), Some(0), Some(0)], // exit codes260+ BTreeMap::new(), // parameter261+ ));262+263+ timing_results.push(BenchmarkResult::new(264+ String::from("sleep 0.1"),265+ 0.1057, // mean266+ 0.0016, // std dev267+ 0.1057, // median268+ 0.0009, // user_mean269+ 0.0011, // system_mean270+ 0.1023, // min271+ 0.1080, // max272+ vec![0.1, 0.1, 0.1], // times273+ vec![Some(0), Some(0), Some(0)], // exit codes274+ BTreeMap::new(), // parameter275+ ));276+277+ let formatted = String::from_utf8(278+ exporter279+ .serialize(&timing_results, Some(Unit::MilliSecond))280+ .unwrap(),281+ )282+ .unwrap();283+284+ let formatted_expected = format!(285+ "{}\286+| `sleep 2` | 2005.0 ± 2.0 | 2002.0 | 2008.0 | 18.97 ± 0.29 |287+| `sleep 0.1` | 105.7 ± 1.6 | 102.3 | 108.0 | 1.00 |288+",289+ table_header("ms".to_string())290+ );291+292+ assert_eq!(formatted_expected, formatted);293+}added:src/export/mod.rs+89 added
1+mod asciidoc;2+mod csv;3+mod json;4+mod markdown;5+6+use self::asciidoc::AsciidocExporter;7+use self::csv::CsvExporter;8+use self::json::JsonExporter;9+use self::markdown::MarkdownExporter;10+11+use std::fs::{File, OpenOptions};12+use std::io::{Result, Write};13+14+use crate::benchmark_result::BenchmarkResult;15+use crate::units::Unit;16+17+/// The desired form of exporter to use for a given file.18+#[derive(Clone)]19+pub enum ExportType {20+ /// Asciidoc Table21+ Asciidoc,22+23+ /// CSV (comma separated values) format24+ Csv,25+26+ /// JSON format27+ Json,28+29+ /// Markdown table30+ Markdown,31+}32+33+/// Interface for different exporters.34+trait Exporter {35+ /// Export the given entries in the serialized form.36+ fn serialize(&self, results: &[BenchmarkResult], unit: Option<Unit>) -> Result<Vec<u8>>;37+}38+39+struct ExporterWithFilename {40+ exporter: Box<dyn Exporter>,41+ filename: String,42+}43+44+/// Handles the management of multiple file exporters.45+pub struct ExportManager {46+ exporters: Vec<ExporterWithFilename>,47+}48+49+impl ExportManager {50+ /// Create a new ExportManager51+ pub fn new() -> ExportManager {52+ ExportManager {53+ exporters: Vec::new(),54+ }55+ }56+57+ /// Add an additional exporter to the ExportManager58+ pub fn add_exporter(&mut self, export_type: ExportType, filename: &str) -> Result<()> {59+ let _ = File::create(filename)?;60+61+ let exporter: Box<dyn Exporter> = match export_type {62+ ExportType::Asciidoc => Box::new(AsciidocExporter::default()),63+ ExportType::Csv => Box::new(CsvExporter::default()),64+ ExportType::Json => Box::new(JsonExporter::default()),65+ ExportType::Markdown => Box::new(MarkdownExporter::default()),66+ };67+ self.exporters.push(ExporterWithFilename {68+ exporter,69+ filename: filename.to_string(),70+ });71+72+ Ok(())73+ }74+75+ /// Write the given results to all Exporters contained within this manager76+ pub fn write_results(&self, results: &[BenchmarkResult], unit: Option<Unit>) -> Result<()> {77+ for e in &self.exporters {78+ let file_content = e.exporter.serialize(results, unit)?;79+ write_to_file(&e.filename, &file_content)?;80+ }81+ Ok(())82+ }83+}84+85+/// Write the given content to a file with the specified name86+fn write_to_file(filename: &str, content: &[u8]) -> Result<()> {87+ let mut file = OpenOptions::new().write(true).open(filename)?;88+ file.write_all(content)89+}deleted:src/hyperfine/export/asciidoc.rs-237 removed
1-use super::Exporter;2-3-use crate::hyperfine::benchmark_result::BenchmarkResult;4-use crate::hyperfine::format::format_duration_value;5-use crate::hyperfine::units::Unit;6-7-use std::io::Result;8-9-#[derive(Default)]10-pub struct AsciidocExporter {}11-12-impl Exporter for AsciidocExporter {13- fn serialize(&self, results: &[BenchmarkResult], unit: Option<Unit>) -> Result<Vec<u8>> {14- let unit = if let Some(unit) = unit {15- // Use the given unit for all entries.16- unit17- } else if let Some(first_result) = results.first() {18- // Use the first BenchmarkResult entry to determine the unit for all entries.19- format_duration_value(first_result.mean, None).120- } else {21- // Default to `Second`.22- Unit::Second23- };24-25- let mut res: Vec<u8> = Vec::new();26- res.append(&mut table_open());27- res.append(&mut table_startend());28- res.append(&mut table_header(unit));29- for result in results {30- res.push(b'\n');31- res.append(&mut table_row(result, unit));32- }33- res.append(&mut table_startend());34-35- Ok(res)36- }37-}38-39-fn table_open() -> Vec<u8> {40- "[cols=\"<,>,>\"]\n".bytes().collect()41-}42-43-fn table_startend() -> Vec<u8> {44- "|===\n".bytes().collect()45-}46-47-fn table_header(unittype: Unit) -> Vec<u8> {48- let unit_short_name = unittype.short_name();49- format!(50- "| Command | Mean [{unit}] | Min…Max [{unit}]\n",51- unit = unit_short_name52- )53- .into_bytes()54-}55-56-fn table_row(entry: &BenchmarkResult, unit: Unit) -> Vec<u8> {57- let form = |val| format_duration_value(val, Some(unit));58- format!(59- "| `{}`\n\60- | {} ± {}\n\61- | {}…{}\n",62- entry.command.replace("|", "\\|"),63- form(entry.mean).0,64- form(entry.stddev).0,65- form(entry.min).0,66- form(entry.max).067- )68- .into_bytes()69-}70-71-/// Ensure various options for the header generate correct results72-#[test]73-fn test_asciidoc_header() {74- let conms: Vec<u8> = "| Command | Mean [ms] | Min…Max [ms]\n".bytes().collect();75- let cons: Vec<u8> = "| Command | Mean [s] | Min…Max [s]\n".bytes().collect();76- let genms = table_header(Unit::MilliSecond);77- let gens = table_header(Unit::Second);78-79- assert_eq!(conms, genms);80- assert_eq!(cons, gens);81-}82-83-/// Ensure each table row is generated properly84-#[test]85-fn test_asciidoc_table_row() {86- use std::collections::BTreeMap;87- let result = BenchmarkResult::new(88- String::from("sleep 1"), // command89- 0.10491992406666667, // mean90- 0.00397851689425097, // stddev91- 0.10491992406666667, // median92- 0.005182013333333333, // user93- 0.0, // system94- 0.1003342584, // min95- 0.10745223440000001, // max96- vec![97- // times98- 0.1003342584,99- 0.10745223440000001,100- 0.10697327940000001,101- ],102- vec![Some(0), Some(0), Some(0)], // exit codes103- BTreeMap::new(), // param104- );105-106- let expms = format!(107- "| `{}`\n\108- | {} ± {}\n\109- | {}…{}\n",110- result.command,111- Unit::MilliSecond.format(result.mean),112- Unit::MilliSecond.format(result.stddev),113- Unit::MilliSecond.format(result.min),114- Unit::MilliSecond.format(result.max)115- )116- .into_bytes();117- let exps = format!(118- "| `{}`\n\119- | {} ± {}\n\120- | {}…{}\n",121- result.command,122- Unit::Second.format(result.mean),123- Unit::Second.format(result.stddev),124- Unit::Second.format(result.min),125- Unit::Second.format(result.max)126- )127- .into_bytes();128-129- let genms = table_row(&result, Unit::MilliSecond);130- let gens = table_row(&result, Unit::Second);131-132- assert_eq!(expms, genms);133- assert_eq!(exps, gens);134-}135-136-/// Ensure commands get properly escaped137-#[test]138-fn test_asciidoc_table_row_command_escape() {139- use std::collections::BTreeMap;140- let result = BenchmarkResult::new(141- String::from("sleep 1|"), // command142- 0.10491992406666667, // mean143- 0.00397851689425097, // stddev144- 0.10491992406666667, // median145- 0.005182013333333333, // user146- 0.0, // system147- 0.1003342584, // min148- 0.10745223440000001, // max149- vec![150- // times151- 0.1003342584,152- 0.10745223440000001,153- 0.10697327940000001,154- ],155- vec![Some(0), Some(0), Some(0)], // exit codes156- BTreeMap::new(), // param157- );158- let exps = format!(159- "| `sleep 1\\|`\n\160- | {} ± {}\n\161- | {}…{}\n",162- Unit::Second.format(result.mean),163- Unit::Second.format(result.stddev),164- Unit::Second.format(result.min),165- Unit::Second.format(result.max)166- )167- .into_bytes();168- let gens = table_row(&result, Unit::Second);169-170- assert_eq!(exps, gens);171-}172-173-/// Integration test174-#[test]175-fn test_asciidoc() {176- use std::collections::BTreeMap;177- let exporter = AsciidocExporter::default();178- // NOTE: results are fabricated, unlike above179- let results = vec![180- BenchmarkResult::new(181- String::from("FOO=1 BAR=2 command | 1"),182- 1.0,183- 2.0,184- 1.0,185- 3.0,186- 4.0,187- 5.0,188- 6.0,189- vec![7.0, 8.0, 9.0],190- vec![Some(0), Some(0), Some(0)],191- {192- let mut params = BTreeMap::new();193- params.insert("foo".into(), "1".into());194- params.insert("bar".into(), "2".into());195- params196- },197- ),198- BenchmarkResult::new(199- String::from("FOO=1 BAR=7 command | 2"),200- 11.0,201- 12.0,202- 11.0,203- 13.0,204- 14.0,205- 15.0,206- 16.0,207- vec![17.0, 18.0, 19.0],208- vec![Some(0), Some(0), Some(0)],209- {210- let mut params = BTreeMap::new();211- params.insert("foo".into(), "1".into());212- params.insert("bar".into(), "7".into());213- params214- },215- ),216- ];217- // NOTE: only testing with s, s/ms is tested elsewhere218- let exps: String = String::from(219- "[cols=\"<,>,>\"]\n\220- |===\n\221- | Command | Mean [s] | Min…Max [s]\n\222- \n\223- | `FOO=1 BAR=2 command \\| 1`\n\224- | 1.000 ± 2.000\n\225- | 5.000…6.000\n\226- \n\227- | `FOO=1 BAR=7 command \\| 2`\n\228- | 11.000 ± 12.000\n\229- | 15.000…16.000\n\230- |===\n\231- ",232- );233- let gens =234- String::from_utf8(exporter.serialize(&results, Some(Unit::Second)).unwrap()).unwrap();235-236- assert_eq!(exps, gens);237-}deleted:src/hyperfine/export/csv.rs-107 removed
1-use super::Exporter;2-3-use crate::hyperfine::benchmark_result::BenchmarkResult;4-use crate::hyperfine::units::Unit;5-6-use std::borrow::Cow;7-use std::io::{Error, ErrorKind, Result};8-9-use csv::WriterBuilder;10-11-#[derive(Default)]12-pub struct CsvExporter {}13-14-impl Exporter for CsvExporter {15- fn serialize(&self, results: &[BenchmarkResult], _unit: Option<Unit>) -> Result<Vec<u8>> {16- let mut writer = WriterBuilder::new().from_writer(vec![]);17-18- {19- let mut headers: Vec<Cow<[u8]>> = [20- // The list of times and exit codes cannot be exported to the CSV file - omit them.21- "command", "mean", "stddev", "median", "user", "system", "min", "max",22- ]23- .iter()24- .map(|x| Cow::Borrowed(x.as_bytes()))25- .collect();26- if let Some(res) = results.first() {27- for param_name in res.parameters.keys() {28- headers.push(Cow::Owned(format!("parameter_{}", param_name).into_bytes()));29- }30- }31- writer.write_record(headers)?;32- }33-34- for res in results {35- let mut fields = vec![Cow::Borrowed(res.command.as_bytes())];36- for f in &[37- res.mean, res.stddev, res.median, res.user, res.system, res.min, res.max,38- ] {39- fields.push(Cow::Owned(f.to_string().into_bytes()))40- }41- for v in res.parameters.values() {42- fields.push(Cow::Borrowed(v.as_bytes()))43- }44- writer.write_record(fields)?;45- }46-47- writer48- .into_inner()49- .map_err(|e| Error::new(ErrorKind::Other, e))50- }51-}52-53-#[test]54-fn test_csv() {55- use std::collections::BTreeMap;56- let exporter = CsvExporter::default();57-58- // NOTE: results are fabricated59- let results = vec![60- BenchmarkResult::new(61- String::from("FOO=one BAR=two command | 1"),62- 1.0,63- 2.0,64- 1.0,65- 3.0,66- 4.0,67- 5.0,68- 6.0,69- vec![7.0, 8.0, 9.0],70- vec![Some(0), Some(0), Some(0)],71- {72- let mut params = BTreeMap::new();73- params.insert("foo".into(), "one".into());74- params.insert("bar".into(), "two".into());75- params76- },77- ),78- BenchmarkResult::new(79- String::from("FOO=one BAR=seven command | 2"),80- 11.0,81- 12.0,82- 11.0,83- 13.0,84- 14.0,85- 15.0,86- 16.5,87- vec![17.0, 18.0, 19.0],88- vec![Some(0), Some(0), Some(0)],89- {90- let mut params = BTreeMap::new();91- params.insert("foo".into(), "one".into());92- params.insert("bar".into(), "seven".into());93- params94- },95- ),96- ];97- let exps: String = String::from(98- "command,mean,stddev,median,user,system,min,max,parameter_bar,parameter_foo\n\99- FOO=one BAR=two command | 1,1,2,1,3,4,5,6,two,one\n\100- FOO=one BAR=seven command | 2,11,12,11,13,14,15,16.5,seven,one\n\101- ",102- );103- let gens =104- String::from_utf8(exporter.serialize(&results, Some(Unit::Second)).unwrap()).unwrap();105-106- assert_eq!(exps, gens);107-}deleted:src/hyperfine/export/json.rs-27 removed
1-use super::Exporter;2-use crate::hyperfine::benchmark_result::BenchmarkResult;3-use crate::hyperfine::units::Unit;4-5-use std::io::{Error, ErrorKind, Result};6-7-use serde::*;8-use serde_json::to_vec_pretty;9-10-#[derive(Serialize, Debug)]11-struct HyperfineSummary<'a> {12- results: &'a [BenchmarkResult],13-}14-15-#[derive(Default)]16-pub struct JsonExporter {}17-18-impl Exporter for JsonExporter {19- fn serialize(&self, results: &[BenchmarkResult], _unit: Option<Unit>) -> Result<Vec<u8>> {20- let mut output = to_vec_pretty(&HyperfineSummary { results });21- for content in output.iter_mut() {22- content.push(b'\n');23- }24-25- output.map_err(|e| Error::new(ErrorKind::Other, e))26- }27-}deleted:src/hyperfine/export/markdown.rs-293 removed
1-use super::Exporter;2-3-use crate::hyperfine::benchmark_result::BenchmarkResult;4-use crate::hyperfine::format::format_duration_value;5-use crate::hyperfine::internal::{compute_relative_speed, BenchmarkResultWithRelativeSpeed};6-use crate::hyperfine::units::Unit;7-8-use std::io::{Error, ErrorKind, Result};9-10-#[derive(Default)]11-pub struct MarkdownExporter {}12-13-impl Exporter for MarkdownExporter {14- fn serialize(&self, results: &[BenchmarkResult], unit: Option<Unit>) -> Result<Vec<u8>> {15- let unit = if let Some(unit) = unit {16- // Use the given unit for all entries.17- unit18- } else if let Some(first_result) = results.first() {19- // Use the first BenchmarkResult entry to determine the unit for all entries.20- format_duration_value(first_result.mean, None).121- } else {22- // Default to `Second`.23- Unit::Second24- };25-26- if let Some(annotated_results) = compute_relative_speed(results) {27- let mut destination = start_table(unit);28-29- for result in annotated_results {30- add_table_row(&mut destination, &result, unit);31- }32-33- Ok(destination)34- } else {35- Err(Error::new(36- ErrorKind::Other,37- "Relative speed comparison is not available for Markdown export.",38- ))39- }40- }41-}42-43-fn table_header(unit_short_name: String) -> String {44- format!(45- "| Command | Mean [{unit}] | Min [{unit}] | Max [{unit}] | Relative |\n|:---|---:|---:|---:|---:|\n",46- unit = unit_short_name47- )48-}49-50-fn start_table(unit: Unit) -> Vec<u8> {51- table_header(unit.short_name()).bytes().collect()52-}53-54-fn add_table_row(dest: &mut Vec<u8>, entry: &BenchmarkResultWithRelativeSpeed, unit: Unit) {55- let result = &entry.result;56- let mean_str = format_duration_value(result.mean, Some(unit)).0;57- let stddev_str = format_duration_value(result.stddev, Some(unit)).0;58- let min_str = format_duration_value(result.min, Some(unit)).0;59- let max_str = format_duration_value(result.max, Some(unit)).0;60- let rel_str = format!("{:.2}", entry.relative_speed);61- let rel_stddev_str = if entry.is_fastest {62- "".into()63- } else {64- format!(" ± {:.2}", entry.relative_speed_stddev)65- };66-67- dest.extend(68- format!(69- "| `{command}` | {mean} ± {stddev} | {min} | {max} | {rel}{rel_stddev} |\n",70- command = result.command.replace("|", "\\|"),71- mean = mean_str,72- stddev = stddev_str,73- min = min_str,74- max = max_str,75- rel = rel_str,76- rel_stddev = rel_stddev_str,77- )78- .as_bytes(),79- );80-}81-82-/// Ensure the markdown output includes the table header and the multiple83-/// benchmark results as a table. The list of actual times is not included84-/// in the output.85-///86-/// This also demonstrates that the first entry's units (ms) are used to set87-/// the units for all entries when the time unit is not given.88-#[test]89-fn test_markdown_format_ms() {90- use std::collections::BTreeMap;91- let exporter = MarkdownExporter::default();92-93- let mut timing_results = vec![];94-95- timing_results.push(BenchmarkResult::new(96- String::from("sleep 0.1"),97- 0.1057, // mean98- 0.0016, // std dev99- 0.1057, // median100- 0.0009, // user_mean101- 0.0011, // system_mean102- 0.1023, // min103- 0.1080, // max104- vec![0.1, 0.1, 0.1], // times105- vec![Some(0), Some(0), Some(0)], // exit codes106- BTreeMap::new(), // parameter107- ));108-109- timing_results.push(BenchmarkResult::new(110- String::from("sleep 2"),111- 2.0050, // mean112- 0.0020, // std dev113- 2.0050, // median114- 0.0009, // user_mean115- 0.0012, // system_mean116- 2.0020, // min117- 2.0080, // max118- vec![2.0, 2.0, 2.0], // times119- vec![Some(0), Some(0), Some(0)], // exit codes120- BTreeMap::new(), // parameter121- ));122-123- let formatted = String::from_utf8(exporter.serialize(&timing_results, None).unwrap()).unwrap();124-125- let formatted_expected = format!(126- "{}\127-| `sleep 0.1` | 105.7 ± 1.6 | 102.3 | 108.0 | 1.00 |128-| `sleep 2` | 2005.0 ± 2.0 | 2002.0 | 2008.0 | 18.97 ± 0.29 |129-",130- table_header("ms".to_string())131- );132-133- assert_eq!(formatted_expected, formatted);134-}135-136-/// This (again) demonstrates that the first entry's units (s) are used to set137-/// the units for all entries when the time unit is not given.138-#[test]139-fn test_markdown_format_s() {140- use std::collections::BTreeMap;141- let exporter = MarkdownExporter::default();142-143- let mut timing_results = vec![];144-145- timing_results.push(BenchmarkResult::new(146- String::from("sleep 2"),147- 2.0050, // mean148- 0.0020, // std dev149- 2.0050, // median150- 0.0009, // user_mean151- 0.0012, // system_mean152- 2.0020, // min153- 2.0080, // max154- vec![2.0, 2.0, 2.0], // times155- vec![Some(0), Some(0), Some(0)], // exit codes156- BTreeMap::new(), // parameter157- ));158-159- timing_results.push(BenchmarkResult::new(160- String::from("sleep 0.1"),161- 0.1057, // mean162- 0.0016, // std dev163- 0.1057, // median164- 0.0009, // user_mean165- 0.0011, // system_mean166- 0.1023, // min167- 0.1080, // max168- vec![0.1, 0.1, 0.1], // times169- vec![Some(0), Some(0), Some(0)], // exit codes170- BTreeMap::new(), // parameter171- ));172-173- let formatted = String::from_utf8(exporter.serialize(&timing_results, None).unwrap()).unwrap();174-175- let formatted_expected = format!(176- "{}\177-| `sleep 2` | 2.005 ± 0.002 | 2.002 | 2.008 | 18.97 ± 0.29 |178-| `sleep 0.1` | 0.106 ± 0.002 | 0.102 | 0.108 | 1.00 |179-",180- table_header("s".to_string())181- );182-183- assert_eq!(formatted_expected, formatted);184-}185-186-/// The given time unit (s) is used to set the units for all entries.187-#[test]188-fn test_markdown_format_time_unit_s() {189- use std::collections::BTreeMap;190- let exporter = MarkdownExporter::default();191-192- let mut timing_results = vec![];193-194- timing_results.push(BenchmarkResult::new(195- String::from("sleep 0.1"),196- 0.1057, // mean197- 0.0016, // std dev198- 0.1057, // median199- 0.0009, // user_mean200- 0.0011, // system_mean201- 0.1023, // min202- 0.1080, // max203- vec![0.1, 0.1, 0.1], // times204- vec![Some(0), Some(0), Some(0)], // exit codes205- BTreeMap::new(), // parameter206- ));207-208- timing_results.push(BenchmarkResult::new(209- String::from("sleep 2"),210- 2.0050, // mean211- 0.0020, // std dev212- 2.0050, // median213- 0.0009, // user_mean214- 0.0012, // system_mean215- 2.0020, // min216- 2.0080, // max217- vec![2.0, 2.0, 2.0], // times218- vec![Some(0), Some(0), Some(0)], // exit codes219- BTreeMap::new(), // parameter220- ));221-222- let formatted = String::from_utf8(223- exporter224- .serialize(&timing_results, Some(Unit::Second))225- .unwrap(),226- )227- .unwrap();228-229- let formatted_expected = format!(230- "{}\231-| `sleep 0.1` | 0.106 ± 0.002 | 0.102 | 0.108 | 1.00 |232-| `sleep 2` | 2.005 ± 0.002 | 2.002 | 2.008 | 18.97 ± 0.29 |233-",234- table_header("s".to_string())235- );236-237- assert_eq!(formatted_expected, formatted);238-}239-240-/// This (again) demonstrates that the given time unit (ms) is used to set241-/// the units for all entries.242-#[test]243-fn test_markdown_format_time_unit_ms() {244- use std::collections::BTreeMap;245- let exporter = MarkdownExporter::default();246-247- let mut timing_results = vec![];248-249- timing_results.push(BenchmarkResult::new(250- String::from("sleep 2"),251- 2.0050, // mean252- 0.0020, // std dev253- 2.0050, // median254- 0.0009, // user_mean255- 0.0012, // system_mean256- 2.0020, // min257- 2.0080, // max258- vec![2.0, 2.0, 2.0], // times259- vec![Some(0), Some(0), Some(0)], // exit codes260- BTreeMap::new(), // parameter261- ));262-263- timing_results.push(BenchmarkResult::new(264- String::from("sleep 0.1"),265- 0.1057, // mean266- 0.0016, // std dev267- 0.1057, // median268- 0.0009, // user_mean269- 0.0011, // system_mean270- 0.1023, // min271- 0.1080, // max272- vec![0.1, 0.1, 0.1], // times273- vec![Some(0), Some(0), Some(0)], // exit codes274- BTreeMap::new(), // parameter275- ));276-277- let formatted = String::from_utf8(278- exporter279- .serialize(&timing_results, Some(Unit::MilliSecond))280- .unwrap(),281- )282- .unwrap();283-284- let formatted_expected = format!(285- "{}\286-| `sleep 2` | 2005.0 ± 2.0 | 2002.0 | 2008.0 | 18.97 ± 0.29 |287-| `sleep 0.1` | 105.7 ± 1.6 | 102.3 | 108.0 | 1.00 |288-",289- table_header("ms".to_string())290- );291-292- assert_eq!(formatted_expected, formatted);293-}deleted:src/hyperfine/export/mod.rs-89 removed
1-mod asciidoc;2-mod csv;3-mod json;4-mod markdown;5-6-use self::asciidoc::AsciidocExporter;7-use self::csv::CsvExporter;8-use self::json::JsonExporter;9-use self::markdown::MarkdownExporter;10-11-use std::fs::{File, OpenOptions};12-use std::io::{Result, Write};13-14-use crate::hyperfine::benchmark_result::BenchmarkResult;15-use crate::hyperfine::units::Unit;16-17-/// The desired form of exporter to use for a given file.18-#[derive(Clone)]19-pub enum ExportType {20- /// Asciidoc Table21- Asciidoc,22-23- /// CSV (comma separated values) format24- Csv,25-26- /// JSON format27- Json,28-29- /// Markdown table30- Markdown,31-}32-33-/// Interface for different exporters.34-trait Exporter {35- /// Export the given entries in the serialized form.36- fn serialize(&self, results: &[BenchmarkResult], unit: Option<Unit>) -> Result<Vec<u8>>;37-}38-39-struct ExporterWithFilename {40- exporter: Box<dyn Exporter>,41- filename: String,42-}43-44-/// Handles the management of multiple file exporters.45-pub struct ExportManager {46- exporters: Vec<ExporterWithFilename>,47-}48-49-impl ExportManager {50- /// Create a new ExportManager51- pub fn new() -> ExportManager {52- ExportManager {53- exporters: Vec::new(),54- }55- }56-57- /// Add an additional exporter to the ExportManager58- pub fn add_exporter(&mut self, export_type: ExportType, filename: &str) -> Result<()> {59- let _ = File::create(filename)?;60-61- let exporter: Box<dyn Exporter> = match export_type {62- ExportType::Asciidoc => Box::new(AsciidocExporter::default()),63- ExportType::Csv => Box::new(CsvExporter::default()),64- ExportType::Json => Box::new(JsonExporter::default()),65- ExportType::Markdown => Box::new(MarkdownExporter::default()),66- };67- self.exporters.push(ExporterWithFilename {68- exporter,69- filename: filename.to_string(),70- });71-72- Ok(())73- }74-75- /// Write the given results to all Exporters contained within this manager76- pub fn write_results(&self, results: &[BenchmarkResult], unit: Option<Unit>) -> Result<()> {77- for e in &self.exporters {78- let file_content = e.exporter.serialize(results, unit)?;79- write_to_file(&e.filename, &file_content)?;80- }81- Ok(())82- }83-}84-85-/// Write the given content to a file with the specified name86-fn write_to_file(filename: &str, content: &[u8]) -> Result<()> {87- let mut file = OpenOptions::new().write(true).open(filename)?;88- file.write_all(content)89-}deleted:src/hyperfine/timer/internal.rs-19 removed
1-use crate::hyperfine::units::Second;2-3-#[derive(Debug, Copy, Clone)]4-pub struct CPUTimes {5- /// Total amount of time spent executing in user mode6- pub user_usec: i64,7-8- /// Total amount of time spent executing in kernel mode9- pub system_usec: i64,10-}11-12-#[derive(Debug, Copy, Clone)]13-pub struct CPUInterval {14- /// Total amount of time spent executing in user mode15- pub user: Second,16-17- /// Total amount of time spent executing in kernel mode18- pub system: Second,19-}deleted:src/hyperfine/timer/mod.rs-28 removed
1-mod internal;2-3-pub mod wallclocktimer;4-5-use cfg_if::cfg_if;6-7-cfg_if! {8- if #[cfg(windows)] {9- mod windows_timer;10- pub use self::windows_timer::get_cpu_timer;11- } else {12- mod unix_timer;13- pub use self::unix_timer::get_cpu_timer;14- }15-}16-use std::process::Child;17-18-/// Defines start functionality of a timer.19-pub trait TimerStart {20- fn start() -> Self;21- fn start_for_process(process: &Child) -> Self;22-}23-24-/// Defines stop functionality of a timer.25-pub trait TimerStop {26- type Result;27- fn stop(&self) -> Self::Result;28-}deleted:src/hyperfine/timer/unix_timer.rs-96 removed
1-#![cfg(not(windows))]2-3-use super::internal::{CPUInterval, CPUTimes};4-use crate::hyperfine::timer::{TimerStart, TimerStop};5-use crate::hyperfine::units::Second;6-7-use std::mem;8-use std::process::Child;9-10-pub fn get_cpu_timer() -> Box<dyn TimerStop<Result = (Second, Second)>> {11- Box::new(CPUTimer::start())12-}13-14-struct CPUTimer {15- start_cpu: CPUTimes,16-}17-18-impl TimerStart for CPUTimer {19- fn start() -> Self {20- CPUTimer {21- start_cpu: get_cpu_times(),22- }23- }24-25- fn start_for_process(_: &Child) -> Self {26- Self::start()27- }28-}29-30-impl TimerStop for CPUTimer {31- type Result = (Second, Second);32-33- fn stop(&self) -> Self::Result {34- let end_cpu = get_cpu_times();35- let cpu_interval = cpu_time_interval(&self.start_cpu, &end_cpu);36- (cpu_interval.user, cpu_interval.system)37- }38-}39-40-/// Read CPU execution times ('user' and 'system')41-fn get_cpu_times() -> CPUTimes {42- use libc::{getrusage, rusage, RUSAGE_CHILDREN};43-44- let result: rusage = unsafe {45- let mut buf = mem::zeroed();46- let success = getrusage(RUSAGE_CHILDREN, &mut buf);47- assert_eq!(0, success);48- buf49- };50-51- const MICROSEC_PER_SEC: i64 = 1000 * 1000;52-53- #[allow(clippy::useless_conversion)]54- CPUTimes {55- user_usec: i64::from(result.ru_utime.tv_sec) * MICROSEC_PER_SEC56- + i64::from(result.ru_utime.tv_usec),57- system_usec: i64::from(result.ru_stime.tv_sec) * MICROSEC_PER_SEC58- + i64::from(result.ru_stime.tv_usec),59- }60-}61-62-/// Compute the time intervals in between two `CPUTimes` snapshots63-fn cpu_time_interval(start: &CPUTimes, end: &CPUTimes) -> CPUInterval {64- CPUInterval {65- user: ((end.user_usec - start.user_usec) as f64) * 1e-6,66- system: ((end.system_usec - start.system_usec) as f64) * 1e-6,67- }68-}69-70-#[cfg(test)]71-use approx::assert_relative_eq;72-73-#[test]74-fn test_cpu_time_interval() {75- let t_a = CPUTimes {76- user_usec: 12345,77- system_usec: 54321,78- };79-80- let t_b = CPUTimes {81- user_usec: 20000,82- system_usec: 70000,83- };84-85- let t_zero = cpu_time_interval(&t_a, &t_a);86- assert!(t_zero.user.abs() < f64::EPSILON);87- assert!(t_zero.system.abs() < f64::EPSILON);88-89- let t_ab = cpu_time_interval(&t_a, &t_b);90- assert_relative_eq!(0.007655, t_ab.user);91- assert_relative_eq!(0.015679, t_ab.system);92-93- let t_ba = cpu_time_interval(&t_b, &t_a);94- assert_relative_eq!(-0.007655, t_ba.user);95- assert_relative_eq!(-0.015679, t_ba.system);96-}deleted:src/hyperfine/timer/wallclocktimer.rs-30 removed
1-use std::process::Child;2-use std::time::Instant;3-4-use crate::hyperfine::timer::{TimerStart, TimerStop};5-use crate::hyperfine::units::Second;6-7-pub struct WallClockTimer {8- start: Instant,9-}10-11-impl TimerStart for WallClockTimer {12- fn start() -> WallClockTimer {13- WallClockTimer {14- start: Instant::now(),15- }16- }17-18- fn start_for_process(_: &Child) -> Self {19- Self::start()20- }21-}22-23-impl TimerStop for WallClockTimer {24- type Result = Second;25-26- fn stop(&self) -> Second {27- let duration = self.start.elapsed();28- duration.as_secs() as f64 + f64::from(duration.subsec_nanos()) * 1e-929- }30-}deleted:src/hyperfine/timer/windows_timer.rs-83 removed
1-#![cfg(windows)]2-3-use super::internal::CPUTimes;4-use crate::hyperfine::timer::{TimerStart, TimerStop};5-use crate::hyperfine::units::Second;6-7-use winapi::um::processthreadsapi::GetProcessTimes;8-use winapi::um::winnt::HANDLE;9-10-use std::mem;11-use std::os::windows::io::{AsRawHandle, RawHandle};12-use std::process::Child;13-14-const HUNDRED_NS_PER_MS: i64 = 10;15-16-pub fn get_cpu_timer(process: &Child) -> Box<dyn TimerStop<Result = (Second, Second)>> {17- Box::new(CPUTimer::start_for_process(process))18-}19-20-struct CPUTimer {21- handle: RawHandle,22-}23-24-impl TimerStart for CPUTimer {25- fn start() -> Self {26- panic!()27- }28-29- fn start_for_process(process: &Child) -> Self {30- CPUTimer {31- handle: process.as_raw_handle(),32- }33- }34-}35-36-impl TimerStop for CPUTimer {37- type Result = (Second, Second);38-39- fn stop(&self) -> Self::Result {40- let times = get_cpu_times(self.handle);41- (42- times.user_usec as f64 * 1e-6,43- times.system_usec as f64 * 1e-6,44- )45- }46-}47-48-/// Read CPU execution times (dummy for now)49-fn get_cpu_times(handle: RawHandle) -> CPUTimes {50- let (user_usec, system_usec) = unsafe {51- let mut _ctime = mem::zeroed();52- let mut _etime = mem::zeroed();53- let mut kernel_time = mem::zeroed();54- let mut user_time = mem::zeroed();55- let res = GetProcessTimes(56- handle as HANDLE,57- &mut _ctime,58- &mut _etime,59- &mut kernel_time,60- &mut user_time,61- );62-63- // GetProcessTimes will exit with non-zero if success as per: https://msdn.microsoft.com/en-us/library/windows/desktop/ms683223(v=vs.85).aspx64- if res != 0 {65- // Extract times as laid out here: https://support.microsoft.com/en-us/help/188768/info-working-with-the-filetime-structure66- // Both user_time and kernel_time are spans that the proces spent in either.67- let user: i64 = (((user_time.dwHighDateTime as i64) << 32)68- + user_time.dwLowDateTime as i64)69- / HUNDRED_NS_PER_MS;70- let kernel: i64 = (((kernel_time.dwHighDateTime as i64) << 32)71- + kernel_time.dwLowDateTime as i64)72- / HUNDRED_NS_PER_MS;73- (user, kernel)74- } else {75- (0, 0)76- }77- };78-79- CPUTimes {80- user_usec,81- system_usec,82- }83-}deleted:src/hyperfine/app.rs-242 removed
1-use atty::Stream;2-use clap::{crate_version, App, AppSettings, Arg, ArgMatches};3-use std::ffi::OsString;4-5-pub fn get_arg_matches<I, T>(args: I) -> ArgMatches<'static>6-where7- I: IntoIterator<Item = T>,8- T: Into<OsString> + Clone,9-{10- let app = build_app();11- app.get_matches_from(args)12-}13-14-/// Build the clap app for parsing command line arguments15-fn build_app() -> App<'static, 'static> {16- let clap_color_setting = if atty::is(Stream::Stdout) {17- AppSettings::ColoredHelp18- } else {19- AppSettings::ColorNever20- };21-22- App::new("hyperfine")23- .version(crate_version!())24- .setting(clap_color_setting)25- .setting(AppSettings::DeriveDisplayOrder)26- .setting(AppSettings::UnifiedHelpMessage)27- .setting(AppSettings::NextLineHelp)28- .setting(AppSettings::HidePossibleValuesInHelp)29- .max_term_width(90)30- .about("A command-line benchmarking tool.")31- .arg(32- Arg::with_name("command")33- .help("Command to benchmark")34- .required(true)35- .multiple(true)36- .empty_values(false),37- )38- .arg(39- Arg::with_name("warmup")40- .long("warmup")41- .short("w")42- .takes_value(true)43- .value_name("NUM")44- .help(45- "Perform NUM warmup runs before the actual benchmark. This can be used \46- to fill (disk) caches for I/O-heavy programs.",47- ),48- )49- .arg(50- Arg::with_name("min-runs")51- .long("min-runs")52- .short("m")53- .takes_value(true)54- .value_name("NUM")55- .help("Perform at least NUM runs for each command (default: 10)."),56- )57- .arg(58- Arg::with_name("max-runs")59- .long("max-runs")60- .short("M")61- .takes_value(true)62- .value_name("NUM")63- .help("Perform at most NUM runs for each command. By default, there is no limit."),64- )65- .arg(66- Arg::with_name("runs")67- .long("runs")68- .conflicts_with_all(&["max-runs", "min-runs"])69- .short("r")70- .takes_value(true)71- .value_name("NUM")72- .help("Perform exactly NUM runs for each command. If this option is not specified, \73- hyperfine automatically determines the number of runs."),74- )75- .arg(76- Arg::with_name("prepare")77- .long("prepare")78- .short("p")79- .takes_value(true)80- .multiple(true)81- .number_of_values(1)82- .value_name("CMD")83- .help(84- "Execute CMD before each timing run. This is useful for \85- clearing disk caches, for example.\nThe --prepare option can \86- be specified once for all commands or multiple times, once for \87- each command. In the latter case, each preparation command will \88- be run prior to the corresponding benchmark command.",89- ),90- )91- .arg(92- Arg::with_name("cleanup")93- .long("cleanup")94- .short("c")95- .takes_value(true)96- .value_name("CMD")97- .help(98- "Execute CMD after the completion of all benchmarking \99- runs for each individual command to be benchmarked. \100- This is useful if the commands to be benchmarked produce \101- artifacts that need to be cleaned up."102- ),103- )104- .arg(105- Arg::with_name("parameter-scan")106- .long("parameter-scan")107- .short("P")108- .takes_value(true)109- .allow_hyphen_values(true)110- .value_names(&["VAR", "MIN", "MAX"])111- .help(112- "Perform benchmark runs for each value in the range MIN..MAX. Replaces the \113- string '{VAR}' in each command by the current parameter value.\n\n \114- Example: hyperfine -P threads 1 8 'make -j {threads}'\n\n\115- This performs benchmarks for 'make -j 1', 'make -j 2', …, 'make -j 8'.",116- ),117- )118- .arg(119- Arg::with_name("parameter-step-size")120- .long("parameter-step-size")121- .short("D")122- .takes_value(true)123- .value_names(&["DELTA"])124- .requires("parameter-scan")125- .help(126- "This argument requires --parameter-scan to be specified as well. \127- Traverse the range MIN..MAX in steps of DELTA.\n\n \128- Example: hyperfine -P delay 0.3 0.7 -D 0.2 'sleep {delay}'\n\n\129- This performs benchmarks for 'sleep 0.3', 'sleep 0.5' and 'sleep 0.7'.",130- ),131- )132- .arg(133- Arg::with_name("parameter-list")134- .long("parameter-list")135- .short("L")136- .takes_value(true)137- .multiple(true)138- .allow_hyphen_values(true)139- .value_names(&["VAR", "VALUES"])140- .conflicts_with_all(&["parameter-scan", "parameter-step-size"])141- .help(142- "Perform benchmark runs for each value in the comma-separated list VALUES. \143- Replaces the string '{VAR}' in each command by the current parameter value\144- .\n\nExample: hyperfine -L compiler gcc,clang '{compiler} -O2 main.cpp'\n\n\145- This performs benchmarks for 'gcc -O2 main.cpp' and 'clang -O2 main.cpp'.\n\n\146- The option can be specified multiple times to run benchmarks for all \147- possible parameter combinations.\n"148- ),149- )150- .arg(151- Arg::with_name("style")152- .long("style")153- .short("s")154- .takes_value(true)155- .value_name("TYPE")156- .possible_values(&["auto", "basic", "full", "nocolor", "color", "none"])157- .help(158- "Set output style type (default: auto). Set this to 'basic' to disable output \159- coloring and interactive elements. Set it to 'full' to enable all effects \160- even if no interactive terminal was detected. Set this to 'nocolor' to \161- keep the interactive output without any colors. Set this to 'color' to keep \162- the colors without any interactive output. Set this to 'none' to disable all \163- the output of the tool.",164- ),165- )166- .arg(167- Arg::with_name("shell")168- .long("shell")169- .short("S")170- .takes_value(true)171- .value_name("SHELL")172- .overrides_with("shell")173- .help("Set the shell to use for executing benchmarked commands."),174- )175- .arg(176- Arg::with_name("ignore-failure")177- .long("ignore-failure")178- .short("i")179- .help("Ignore non-zero exit codes of the benchmarked programs."),180- )181- .arg(182- Arg::with_name("time-unit")183- .long("time-unit")184- .short("u")185- .takes_value(true)186- .value_name("UNIT")187- .possible_values(&["millisecond", "second"])188- .help("Set the time unit to be used. Possible values: millisecond, second."),189- )190- .arg(191- Arg::with_name("export-asciidoc")192- .long("export-asciidoc")193- .takes_value(true)194- .value_name("FILE")195- .help("Export the timing summary statistics as an AsciiDoc table to the given FILE."),196- )197- .arg(198- Arg::with_name("export-csv")199- .long("export-csv")200- .takes_value(true)201- .value_name("FILE")202- .help("Export the timing summary statistics as CSV to the given FILE. If you need \203- the timing results for each individual run, use the JSON export format."),204- )205- .arg(206- Arg::with_name("export-json")207- .long("export-json")208- .takes_value(true)209- .value_name("FILE")210- .help("Export the timing summary statistics and timings of individual runs as JSON to the given FILE."),211- )212- .arg(213- Arg::with_name("export-markdown")214- .long("export-markdown")215- .takes_value(true)216- .value_name("FILE")217- .help("Export the timing summary statistics as a Markdown table to the given FILE."),218- )219- .arg(220- Arg::with_name("show-output")221- .long("show-output")222- .conflicts_with("style")223- .help(224- "Print the stdout and stderr of the benchmark instead of suppressing it. \225- This will increase the time it takes for benchmarks to run, \226- so it should only be used for debugging purposes or \227- when trying to benchmark output speed.",228- ),229- )230- .arg(231- Arg::with_name("command-name")232- .long("command-name")233- .short("n")234- .takes_value(true)235- .multiple(true)236- .number_of_values(1)237- .value_name("NAME")238- .help("Give a meaningful name to a command"),239- )240- .help_message("Print this help message.")241- .version_message("Show version information.")242-}deleted:src/hyperfine/benchmark_result.rs-77 removed
1-use serde::Serialize;2-use std::collections::BTreeMap;3-4-use crate::hyperfine::units::Second;5-6-/// Set of values that will be exported.7-// NOTE: `serde` is used for JSON serialization, but not for CSV serialization due to the8-// `parameters` map. Update `src/hyperfine/export/csv.rs` with new fields, as appropriate.9-#[derive(Debug, Default, Clone, Serialize, PartialEq)]10-pub struct BenchmarkResult {11- /// The command that was run12- pub command: String,13-14- /// The mean run time15- pub mean: Second,16-17- /// The standard deviation of all run times18- pub stddev: Second,19-20- /// The median run time21- pub median: Second,22-23- /// Time spend in user space24- pub user: Second,25-26- /// Time spent in system space27- pub system: Second,28-29- /// Min time measured30- pub min: Second,31-32- /// Max time measured33- pub max: Second,34-35- /// All run time measurements36- #[serde(skip_serializing_if = "Option::is_none")]37- pub times: Option<Vec<Second>>,38-39- /// All run exit codes40- pub exit_codes: Vec<Option<i32>>,41-42- /// Any parameter values used43- #[serde(skip_serializing_if = "BTreeMap::is_empty")]44- pub parameters: BTreeMap<String, String>,45-}46-47-impl BenchmarkResult {48- /// Create a new entry with the given values.49- #[allow(clippy::too_many_arguments)]50- pub fn new(51- command: String,52- mean: Second,53- stddev: Second,54- median: Second,55- user: Second,56- system: Second,57- min: Second,58- max: Second,59- times: Vec<Second>,60- exit_codes: Vec<Option<i32>>,61- parameters: BTreeMap<String, String>,62- ) -> Self {63- BenchmarkResult {64- command,65- mean,66- stddev,67- median,68- user,69- system,70- min,71- max,72- times: Some(times),73- exit_codes,74- parameters,75- }76- }77-}deleted:src/hyperfine/benchmark.rs-484 removed
1-use std::cmp;2-use std::io;3-use std::process::{ExitStatus, Stdio};4-5-use colored::*;6-use statistical::{mean, median, standard_deviation};7-8-use crate::hyperfine::benchmark_result::BenchmarkResult;9-use crate::hyperfine::command::Command;10-use crate::hyperfine::format::{format_duration, format_duration_unit};11-use crate::hyperfine::internal::{get_progress_bar, max, min, MIN_EXECUTION_TIME};12-use crate::hyperfine::options::{CmdFailureAction, HyperfineOptions, OutputStyleOption};13-use crate::hyperfine::outlier_detection::{modified_zscores, OUTLIER_THRESHOLD};14-use crate::hyperfine::shell::execute_and_time;15-use crate::hyperfine::timer::wallclocktimer::WallClockTimer;16-use crate::hyperfine::timer::{TimerStart, TimerStop};17-use crate::hyperfine::units::Second;18-use crate::hyperfine::warnings::Warnings;19-20-/// Results from timing a single shell command21-#[derive(Debug, Default, Copy, Clone)]22-pub struct TimingResult {23- /// Wall clock time24- pub time_real: Second,25-26- /// Time spent in user mode27- pub time_user: Second,28-29- /// Time spent in kernel mode30- pub time_system: Second,31-}32-33-/// Correct for shell spawning time34-fn subtract_shell_spawning_time(time: Second, shell_spawning_time: Second) -> Second {35- if time < shell_spawning_time {36- 0.037- } else {38- time - shell_spawning_time39- }40-}41-42-/// Run the given shell command and measure the execution time43-pub fn time_shell_command(44- shell: &str,45- command: &Command<'_>,46- show_output: bool,47- failure_action: CmdFailureAction,48- shell_spawning_time: Option<TimingResult>,49-) -> io::Result<(TimingResult, ExitStatus)> {50- let (stdout, stderr) = if show_output {51- (Stdio::inherit(), Stdio::inherit())52- } else {53- (Stdio::null(), Stdio::null())54- };55-56- let wallclock_timer = WallClockTimer::start();57- let result = execute_and_time(stdout, stderr, &command.get_shell_command(), shell)?;58- let mut time_real = wallclock_timer.stop();59-60- let mut time_user = result.user_time;61- let mut time_system = result.system_time;62-63- if failure_action == CmdFailureAction::RaiseError && !result.status.success() {64- return Err(io::Error::new(65- io::ErrorKind::Other,66- format!(67- "{}. \68- Use the '-i'/'--ignore-failure' option if you want to ignore this. \69- Alternatively, use the '--show-output' option to debug what went wrong.",70- result.status.code().map_or(71- "The process has been terminated by a signal".into(),72- |c| format!("Command terminated with non-zero exit code: {}", c)73- )74- ),75- ));76- }77-78- // Correct for shell spawning time79- if let Some(spawning_time) = shell_spawning_time {80- time_real = subtract_shell_spawning_time(time_real, spawning_time.time_real);81- time_user = subtract_shell_spawning_time(time_user, spawning_time.time_user);82- time_system = subtract_shell_spawning_time(time_system, spawning_time.time_system);83- }84-85- Ok((86- TimingResult {87- time_real,88- time_user,89- time_system,90- },91- result.status,92- ))93-}94-95-/// Measure the average shell spawning time96-pub fn mean_shell_spawning_time(97- shell: &str,98- style: OutputStyleOption,99- show_output: bool,100-) -> io::Result<TimingResult> {101- const COUNT: u64 = 50;102- let progress_bar = if style != OutputStyleOption::Disabled {103- Some(get_progress_bar(104- COUNT,105- "Measuring shell spawning time",106- style,107- ))108- } else {109- None110- };111-112- let mut times_real: Vec<Second> = vec![];113- let mut times_user: Vec<Second> = vec![];114- let mut times_system: Vec<Second> = vec![];115-116- for _ in 0..COUNT {117- // Just run the shell without any command118- let res = time_shell_command(119- shell,120- &Command::new(None, ""),121- show_output,122- CmdFailureAction::RaiseError,123- None,124- );125-126- match res {127- Err(_) => {128- let shell_cmd = if cfg!(windows) {129- format!("{} /C \"\"", shell)130- } else {131- format!("{} -c \"\"", shell)132- };133-134- return Err(io::Error::new(135- io::ErrorKind::Other,136- format!(137- "Could not measure shell execution time. \138- Make sure you can run '{}'.",139- shell_cmd140- ),141- ));142- }143- Ok((r, _)) => {144- times_real.push(r.time_real);145- times_user.push(r.time_user);146- times_system.push(r.time_system);147- }148- }149-150- if let Some(bar) = progress_bar.as_ref() {151- bar.inc(1)152- }153- }154-155- if let Some(bar) = progress_bar.as_ref() {156- bar.finish_and_clear()157- }158-159- Ok(TimingResult {160- time_real: mean(×_real),161- time_user: mean(×_user),162- time_system: mean(×_system),163- })164-}165-166-fn run_intermediate_command(167- shell: &str,168- command: &Option<Command<'_>>,169- show_output: bool,170- error_output: &'static str,171-) -> io::Result<TimingResult> {172- if let Some(ref cmd) = command {173- let res = time_shell_command(shell, cmd, show_output, CmdFailureAction::RaiseError, None);174- if res.is_err() {175- return Err(io::Error::new(io::ErrorKind::Other, error_output));176- }177- return res.map(|r| r.0);178- }179- Ok(TimingResult {180- ..Default::default()181- })182-}183-184-/// Run the command specified by `--prepare`.185-fn run_preparation_command(186- shell: &str,187- command: &Option<Command<'_>>,188- show_output: bool,189-) -> io::Result<TimingResult> {190- let error_output = "The preparation command terminated with a non-zero exit code. \191- Append ' || true' to the command if you are sure that this can be ignored.";192-193- run_intermediate_command(shell, command, show_output, error_output)194-}195-196-/// Run the command specified by `--cleanup`.197-fn run_cleanup_command(198- shell: &str,199- command: &Option<Command<'_>>,200- show_output: bool,201-) -> io::Result<TimingResult> {202- let error_output = "The cleanup command terminated with a non-zero exit code. \203- Append ' || true' to the command if you are sure that this can be ignored.";204-205- run_intermediate_command(shell, command, show_output, error_output)206-}207-208-#[cfg(unix)]209-fn extract_exit_code(status: ExitStatus) -> Option<i32> {210- use std::os::unix::process::ExitStatusExt;211-212- /* From the ExitStatus::code documentation:213- "On Unix, this will return None if the process was terminated by a signal."214- In that case, ExitStatusExt::signal should never return None.215- */216- status.code().or_else(||217- /* To differentiate between "normal" exit codes and signals, we are using218- something similar to bash exit codes (https://tldp.org/LDP/abs/html/exitcodes.html)219- by adding 128 to a signal integer value.220- */221- status.signal().map(|s| 128 + s))222-}223-224-#[cfg(not(unix))]225-fn extract_exit_code(status: ExitStatus) -> Option<i32> {226- status.code()227-}228-229-/// Run the benchmark for a single shell command230-pub fn run_benchmark(231- num: usize,232- cmd: &Command<'_>,233- shell_spawning_time: TimingResult,234- options: &HyperfineOptions,235-) -> io::Result<BenchmarkResult> {236- let command_name = cmd.get_name();237- if options.output_style != OutputStyleOption::Disabled {238- println!(239- "{}{}: {}",240- "Benchmark ".bold(),241- (num + 1).to_string().bold(),242- command_name,243- );244- }245-246- let mut times_real: Vec<Second> = vec![];247- let mut times_user: Vec<Second> = vec![];248- let mut times_system: Vec<Second> = vec![];249- let mut exit_codes: Vec<Option<i32>> = vec![];250- let mut all_succeeded = true;251-252- // Run init command253- let prepare_cmd = options.preparation_command.as_ref().map(|values| {254- let preparation_command = if values.len() == 1 {255- &values[0]256- } else {257- &values[num]258- };259- Command::new_parametrized(None, preparation_command, cmd.get_parameters().clone())260- });261-262- // Warmup phase263- if options.warmup_count > 0 {264- let progress_bar = if options.output_style != OutputStyleOption::Disabled {265- Some(get_progress_bar(266- options.warmup_count,267- "Performing warmup runs",268- options.output_style,269- ))270- } else {271- None272- };273-274- for _ in 0..options.warmup_count {275- let _ = run_preparation_command(&options.shell, &prepare_cmd, options.show_output)?;276- let _ = time_shell_command(277- &options.shell,278- cmd,279- options.show_output,280- options.failure_action,281- None,282- )?;283- if let Some(bar) = progress_bar.as_ref() {284- bar.inc(1)285- }286- }287- if let Some(bar) = progress_bar.as_ref() {288- bar.finish_and_clear()289- }290- }291-292- // Set up progress bar (and spinner for initial measurement)293- let progress_bar = if options.output_style != OutputStyleOption::Disabled {294- Some(get_progress_bar(295- options.runs.min,296- "Initial time measurement",297- options.output_style,298- ))299- } else {300- None301- };302-303- let prepare_res = run_preparation_command(&options.shell, &prepare_cmd, options.show_output)?;304-305- // Initial timing run306- let (res, status) = time_shell_command(307- &options.shell,308- cmd,309- options.show_output,310- options.failure_action,311- Some(shell_spawning_time),312- )?;313- let success = status.success();314-315- // Determine number of benchmark runs316- let runs_in_min_time = (options.min_time_sec317- / (res.time_real + prepare_res.time_real + shell_spawning_time.time_real))318- as u64;319-320- let count = {321- let min = cmp::max(runs_in_min_time, options.runs.min);322-323- options324- .runs325- .max326- .as_ref()327- .map(|max| cmp::min(min, *max))328- .unwrap_or(min)329- };330-331- let count_remaining = count - 1;332-333- // Save the first result334- times_real.push(res.time_real);335- times_user.push(res.time_user);336- times_system.push(res.time_system);337- exit_codes.push(extract_exit_code(status));338-339- all_succeeded = all_succeeded && success;340-341- // Re-configure the progress bar342- if let Some(bar) = progress_bar.as_ref() {343- bar.set_length(count)344- }345- if let Some(bar) = progress_bar.as_ref() {346- bar.inc(1)347- }348-349- // Gather statistics350- for _ in 0..count_remaining {351- run_preparation_command(&options.shell, &prepare_cmd, options.show_output)?;352-353- let msg = {354- let mean = format_duration(mean(×_real), options.time_unit);355- format!("Current estimate: {}", mean.to_string().green())356- };357-358- if let Some(bar) = progress_bar.as_ref() {359- bar.set_message(msg.to_owned())360- }361-362- let (res, status) = time_shell_command(363- &options.shell,364- cmd,365- options.show_output,366- options.failure_action,367- Some(shell_spawning_time),368- )?;369- let success = status.success();370-371- times_real.push(res.time_real);372- times_user.push(res.time_user);373- times_system.push(res.time_system);374- exit_codes.push(extract_exit_code(status));375-376- all_succeeded = all_succeeded && success;377-378- if let Some(bar) = progress_bar.as_ref() {379- bar.inc(1)380- }381- }382-383- if let Some(bar) = progress_bar.as_ref() {384- bar.finish_and_clear()385- }386-387- // Compute statistical quantities388- let t_num = times_real.len();389- let t_mean = mean(×_real);390- let t_stddev = standard_deviation(×_real, Some(t_mean));391- let t_median = median(×_real);392- let t_min = min(×_real);393- let t_max = max(×_real);394-395- let user_mean = mean(×_user);396- let system_mean = mean(×_system);397-398- // Formatting and console output399- let (mean_str, time_unit) = format_duration_unit(t_mean, options.time_unit);400- let stddev_str = format_duration(t_stddev, Some(time_unit));401- let min_str = format_duration(t_min, Some(time_unit));402- let max_str = format_duration(t_max, Some(time_unit));403- let num_str = format!("{} runs", t_num);404-405- let user_str = format_duration(user_mean, Some(time_unit));406- let system_str = format_duration(system_mean, Some(time_unit));407-408- if options.output_style != OutputStyleOption::Disabled {409- println!(410- " Time ({} ± {}): {:>8} ± {:>8} [User: {}, System: {}]",411- "mean".green().bold(),412- "σ".green(),413- mean_str.green().bold(),414- stddev_str.green(),415- user_str.blue(),416- system_str.blue()417- );418-419- println!(420- " Range ({} … {}): {:>8} … {:>8} {}",421- "min".cyan(),422- "max".purple(),423- min_str.cyan(),424- max_str.purple(),425- num_str.dimmed()426- );427- }428-429- // Warnings430- let mut warnings = vec![];431-432- // Check execution time433- if times_real.iter().any(|&t| t < MIN_EXECUTION_TIME) {434- warnings.push(Warnings::FastExecutionTime);435- }436-437- // Check programm exit codes438- if !all_succeeded {439- warnings.push(Warnings::NonZeroExitCode);440- }441-442- // Run outlier detection443- let scores = modified_zscores(×_real);444- if scores[0] > OUTLIER_THRESHOLD {445- warnings.push(Warnings::SlowInitialRun(times_real[0]));446- } else if scores.iter().any(|&s| s.abs() > OUTLIER_THRESHOLD) {447- warnings.push(Warnings::OutliersDetected);448- }449-450- if !warnings.is_empty() {451- eprintln!(" ");452-453- for warning in &warnings {454- eprintln!(" {}: {}", "Warning".yellow(), warning);455- }456- }457-458- if options.output_style != OutputStyleOption::Disabled {459- println!(" ");460- }461-462- // Run cleanup command463- let cleanup_cmd = options.cleanup_command.as_ref().map(|cleanup_command| {464- Command::new_parametrized(None, cleanup_command, cmd.get_parameters().clone())465- });466- run_cleanup_command(&options.shell, &cleanup_cmd, options.show_output)?;467-468- Ok(BenchmarkResult::new(469- command_name,470- t_mean,471- t_stddev,472- t_median,473- user_mean,474- system_mean,475- t_min,476- t_max,477- times_real,478- exit_codes,479- cmd.get_parameters()480- .iter()481- .map(|(name, value)| ((*name).to_string(), value.to_string()))482- .collect(),483- ))484-}deleted:src/hyperfine/command.rs-115 removed
1-use std::collections::BTreeMap;2-use std::fmt;3-4-use super::types::ParameterValue;5-6-/// A command that should be benchmarked.7-#[derive(Debug, Clone, PartialEq, Eq)]8-pub struct Command<'a> {9- /// The command name (without parameter substitution)10- name: Option<&'a str>,11-12- /// The command that should be executed (without parameter substitution)13- expression: &'a str,14-15- /// Zero or more parameter values.16- parameters: Vec<(&'a str, ParameterValue)>,17-}18-19-impl<'a> Command<'a> {20- pub fn new(name: Option<&'a str>, expression: &'a str) -> Command<'a> {21- Command {22- name,23- expression,24- parameters: Vec::new(),25- }26- }27-28- pub fn new_parametrized(29- name: Option<&'a str>,30- expression: &'a str,31- parameters: Vec<(&'a str, ParameterValue)>,32- ) -> Command<'a> {33- Command {34- name,35- expression,36- parameters,37- }38- }39-40- pub fn get_name(&self) -> String {41- self.name.map_or_else(42- || self.get_shell_command(),43- |name| self.replace_parameters_in(name),44- )45- }46-47- pub fn get_shell_command(&self) -> String {48- self.replace_parameters_in(self.expression)49- }50-51- pub fn get_parameters(&self) -> &Vec<(&'a str, ParameterValue)> {52- &self.parameters53- }54-55- fn replace_parameters_in(&self, original: &str) -> String {56- let mut result = String::new();57- let mut replacements = BTreeMap::<String, String>::new();58- for (param_name, param_value) in &self.parameters {59- replacements.insert(60- format!("{{{param_name}}}", param_name = param_name),61- param_value.to_string(),62- );63- }64- let mut remaining = original;65- // Manually replace consecutive occurrences to avoid double-replacing: e.g.,66- //67- // hyperfine -L foo 'a,{bar}' -L bar 'baz,quux' 'echo {foo} {bar}'68- //69- // should not ever run 'echo baz baz'. See `test_get_shell_command_nonoverlapping`.70- 'outer: while let Some(head) = remaining.chars().next() {71- for (k, v) in &replacements {72- if remaining.starts_with(k.as_str()) {73- result.push_str(v);74- remaining = &remaining[k.len()..];75- continue 'outer;76- }77- }78- result.push(head);79- remaining = &remaining[head.len_utf8()..];80- }81- result82- }83-}84-85-#[test]86-fn test_get_shell_command_nonoverlapping() {87- let cmd = Command::new_parametrized(88- None,89- "echo {foo} {bar}",90- vec![91- ("foo", ParameterValue::Text("{bar} baz".into())),92- ("bar", ParameterValue::Text("quux".into())),93- ],94- );95- assert_eq!(cmd.get_shell_command(), "echo {bar} baz quux");96-}97-98-#[test]99-fn test_get_parameterized_command_name() {100- let cmd = Command::new_parametrized(101- Some("name-{bar}-{foo}"),102- "echo {foo} {bar}",103- vec![104- ("foo", ParameterValue::Text("baz".into())),105- ("bar", ParameterValue::Text("quux".into())),106- ],107- );108- assert_eq!(cmd.get_name(), "name-quux-baz");109-}110-111-impl<'a> fmt::Display for Command<'a> {112- fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {113- write!(f, "{}", self.get_shell_command())114- }115-}deleted:src/hyperfine/error.rs-91 removed
1-use rust_decimal::Error as DecimalError;2-use std::error::Error;3-use std::fmt;4-use std::num;5-use std::num::ParseIntError;6-7-#[derive(Debug)]8-pub enum ParameterScanError {9- ParseIntError(num::ParseIntError),10- ParseDecimalError(DecimalError),11- EmptyRange,12- TooLarge,13- ZeroStep,14- StepRequired,15- UnexpectedCommandNameCount(usize, usize),16-}17-18-impl From<num::ParseIntError> for ParameterScanError {19- fn from(e: num::ParseIntError) -> ParameterScanError {20- ParameterScanError::ParseIntError(e)21- }22-}23-24-impl From<DecimalError> for ParameterScanError {25- fn from(e: DecimalError) -> ParameterScanError {26- ParameterScanError::ParseDecimalError(e)27- }28-}29-30-impl fmt::Display for ParameterScanError {31- fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {32- match *self {33- ParameterScanError::ParseIntError(ref e) => write!(f, "{}", e),34- ParameterScanError::ParseDecimalError(ref e) => write!(f, "{}", e),35- ParameterScanError::EmptyRange => write!(f, "Empty parameter range"),36- ParameterScanError::TooLarge => write!(f, "Parameter range is too large"),37- ParameterScanError::ZeroStep => write!(f, "Zero is not a valid parameter step"),38- ParameterScanError::StepRequired => write!(39- f,40- "A step size is required when the range bounds are \41- floating point numbers. The step size can be specified \42- with the '--parameter-step-size' parameter"43- ),44- ParameterScanError::UnexpectedCommandNameCount(real, expected) => {45- write!(46- f,47- "'--command-name' has been specified {} times. It has to appear exactly once, or exactly {} times (number of benchmarks)",48- real, expected49- )50- }51- }52- }53-}54-55-impl Error for ParameterScanError {}56-57-#[derive(Debug)]58-pub enum OptionsError<'a> {59- RunsBelowTwo,60- EmptyRunsRange,61- TooManyCommandNames(usize),62- UnexpectedCommandNameCount(usize, usize),63- NumericParsingError(&'a str, ParseIntError),64-}65-66-impl<'a> fmt::Display for OptionsError<'a> {67- fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {68- match *self {69- OptionsError::EmptyRunsRange => write!(f, "Empty runs range"),70- OptionsError::RunsBelowTwo => write!(f, "Number of runs below two"),71- OptionsError::TooManyCommandNames(n) => {72- write!(f, "Too many --command-name options: expected {} at most", n)73- }74- OptionsError::UnexpectedCommandNameCount(real, expected) => {75- write!(76- f,77- "'--command-name' has been specified {} times. It has to appear exactly once, or exactly {} times (number of benchmarks)",78- real, expected79- )80- }81- OptionsError::NumericParsingError(cmd, ref err) => write!(82- f,83- "Could not read numeric argument to '--{cmd}': {err}",84- cmd = cmd,85- err = err86- ),87- }88- }89-}90-91-impl<'a> Error for OptionsError<'a> {}deleted:src/hyperfine/format.rs-65 removed
1-use crate::hyperfine::units::{Second, Unit};2-3-/// Format the given duration as a string. The output-unit can be enforced by setting `unit` to4-/// `Some(target_unit)`. If `unit` is `None`, it will be determined automatically.5-pub fn format_duration(duration: Second, unit: Option<Unit>) -> String {6- let (duration_fmt, _) = format_duration_unit(duration, unit);7- duration_fmt8-}9-10-/// Like `format_duration`, but returns the target unit as well.11-pub fn format_duration_unit(duration: Second, unit: Option<Unit>) -> (String, Unit) {12- let (out_str, out_unit) = format_duration_value(duration, unit);13-14- (format!("{} {}", out_str, out_unit.short_name()), out_unit)15-}16-17-/// Like `format_duration`, but returns the target unit as well.18-pub fn format_duration_value(duration: Second, unit: Option<Unit>) -> (String, Unit) {19- if (duration < 1.0 && unit.is_none()) || unit == Some(Unit::MilliSecond) {20- (Unit::MilliSecond.format(duration), Unit::MilliSecond)21- } else {22- (Unit::Second.format(duration), Unit::Second)23- }24-}25-26-#[test]27-fn test_format_duration_unit_basic() {28- let (out_str, out_unit) = format_duration_unit(1.3, None);29-30- assert_eq!("1.300 s", out_str);31- assert_eq!(Unit::Second, out_unit);32-33- let (out_str, out_unit) = format_duration_unit(1.0, None);34-35- assert_eq!("1.000 s", out_str);36- assert_eq!(Unit::Second, out_unit);37-38- let (out_str, out_unit) = format_duration_unit(0.999, None);39-40- assert_eq!("999.0 ms", out_str);41- assert_eq!(Unit::MilliSecond, out_unit);42-43- let (out_str, out_unit) = format_duration_unit(0.0, None);44-45- assert_eq!("0.0 ms", out_str);46- assert_eq!(Unit::MilliSecond, out_unit);47-48- let (out_str, out_unit) = format_duration_unit(1000.0, None);49-50- assert_eq!("1000.000 s", out_str);51- assert_eq!(Unit::Second, out_unit);52-}53-54-#[test]55-fn test_format_duration_unit_with_unit() {56- let (out_str, out_unit) = format_duration_unit(1.3, Some(Unit::Second));57-58- assert_eq!("1.300 s", out_str);59- assert_eq!(Unit::Second, out_unit);60-61- let (out_str, out_unit) = format_duration_unit(1.3, Some(Unit::MilliSecond));62-63- assert_eq!("1300.0 ms", out_str);64- assert_eq!(Unit::MilliSecond, out_unit);65-}deleted:src/hyperfine/internal.rs-255 removed
1-use colored::*;2-use indicatif::{ProgressBar, ProgressStyle};3-4-use crate::hyperfine::benchmark_result::BenchmarkResult;5-use crate::hyperfine::options::OutputStyleOption;6-use crate::hyperfine::units::{Scalar, Second};7-8-use std::cmp::Ordering;9-use std::iter::Iterator;10-11-/// Threshold for warning about fast execution time12-pub const MIN_EXECUTION_TIME: Second = 5e-3;13-14-#[cfg(not(windows))]15-const TICK_SETTINGS: (&str, u64) = ("⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏ ", 80);16-17-#[cfg(windows)]18-const TICK_SETTINGS: (&str, u64) = (r"+-x| ", 200);19-20-/// Return a pre-configured progress bar21-pub fn get_progress_bar(length: u64, msg: &str, option: OutputStyleOption) -> ProgressBar {22- let progressbar_style = match option {23- OutputStyleOption::Basic | OutputStyleOption::Color => ProgressStyle::default_bar(),24- _ => ProgressStyle::default_spinner()25- .tick_chars(TICK_SETTINGS.0)26- .template(" {spinner} {msg:<30} {wide_bar} ETA {eta_precise}"),27- };28-29- let progress_bar = match option {30- OutputStyleOption::Basic | OutputStyleOption::Color => ProgressBar::hidden(),31- _ => ProgressBar::new(length),32- };33- progress_bar.set_style(progressbar_style);34- progress_bar.enable_steady_tick(TICK_SETTINGS.1);35- progress_bar.set_message(msg.to_owned());36-37- progress_bar38-}39-40-/// A max function for f64's without NaNs41-pub fn max(vals: &[f64]) -> f64 {42- *vals43- .iter()44- .max_by(|a, b| a.partial_cmp(b).unwrap())45- .unwrap()46-}47-48-/// A min function for f64's without NaNs49-pub fn min(vals: &[f64]) -> f64 {50- *vals51- .iter()52- .min_by(|a, b| a.partial_cmp(b).unwrap())53- .unwrap()54-}55-56-#[derive(Debug)]57-pub struct BenchmarkResultWithRelativeSpeed<'a> {58- pub result: &'a BenchmarkResult,59- pub relative_speed: Scalar,60- pub relative_speed_stddev: Scalar,61- pub is_fastest: bool,62-}63-64-fn compare_mean_time(l: &BenchmarkResult, r: &BenchmarkResult) -> Ordering {65- l.mean.partial_cmp(&r.mean).unwrap_or(Ordering::Equal)66-}67-68-pub fn compute_relative_speed(69- results: &[BenchmarkResult],70-) -> Option<Vec<BenchmarkResultWithRelativeSpeed>> {71- let fastest: &BenchmarkResult = results72- .iter()73- .min_by(|&l, &r| compare_mean_time(l, r))74- .expect("at least one benchmark result");75-76- if fastest.mean == 0.0 {77- return None;78- }79-80- Some(81- results82- .iter()83- .map(|result| {84- let ratio = result.mean / fastest.mean;85-86- // https://en.wikipedia.org/wiki/Propagation_of_uncertainty#Example_formulas87- // Covariance asssumed to be 0, i.e. variables are assumed to be independent88- let ratio_stddev = ratio89- * ((result.stddev / result.mean).powi(2)90- + (fastest.stddev / fastest.mean).powi(2))91- .sqrt();92-93- BenchmarkResultWithRelativeSpeed {94- result,95- relative_speed: ratio,96- relative_speed_stddev: ratio_stddev,97- is_fastest: result == fastest,98- }99- })100- .collect(),101- )102-}103-104-pub fn write_benchmark_comparison(results: &[BenchmarkResult]) {105- if results.len() < 2 {106- return;107- }108-109- if let Some(mut annotated_results) = compute_relative_speed(results) {110- annotated_results.sort_by(|l, r| compare_mean_time(l.result, r.result));111-112- let fastest = &annotated_results[0];113- let others = &annotated_results[1..];114-115- println!("{}", "Summary".bold());116- println!(" '{}' ran", fastest.result.command.cyan());117-118- for item in others {119- println!(120- "{} ± {} times faster than '{}'",121- format!("{:8.2}", item.relative_speed).bold().green(),122- format!("{:.2}", item.relative_speed_stddev).green(),123- &item.result.command.magenta()124- );125- }126- } else {127- eprintln!(128- "{}: The benchmark comparison could not be computed as some benchmark times are zero. \129- This could be caused by background interference during the initial calibration phase \130- of hyperfine, in combination with very fast commands (faster than a few milliseconds). \131- Try to re-run the benchmark on a quiet system. If it does not help, you command is \132- most likely too fast to be accurately benchmarked by hyperfine.",133- "Note".bold().red()134- );135- }136-}137-138-#[test]139-fn test_max() {140- let assert_float_eq = |a, b| {141- assert!((a - b) < f64::EPSILON);142- };143-144- assert_float_eq(1.0, max(&[1.0]));145- assert_float_eq(-1.0, max(&[-1.0]));146- assert_float_eq(-1.0, max(&[-2.0, -1.0]));147- assert_float_eq(1.0, max(&[-1.0, 1.0]));148- assert_float_eq(1.0, max(&[-1.0, 1.0, 0.0]));149-}150-151-#[cfg(test)]152-fn create_result(name: &str, mean: Scalar) -> BenchmarkResult {153- use std::collections::BTreeMap;154-155- BenchmarkResult {156- command: name.into(),157- mean,158- stddev: 1.0,159- median: mean,160- user: mean,161- system: 0.0,162- min: mean,163- max: mean,164- times: None,165- exit_codes: Vec::new(),166- parameters: BTreeMap::new(),167- }168-}169-170-#[test]171-fn test_compute_relative_speed() {172- use approx::assert_relative_eq;173-174- let results = vec![175- create_result("cmd1", 3.0),176- create_result("cmd2", 2.0),177- create_result("cmd3", 5.0),178- ];179-180- let annotated_results = compute_relative_speed(&results).unwrap();181-182- assert_relative_eq!(1.5, annotated_results[0].relative_speed);183- assert_relative_eq!(1.0, annotated_results[1].relative_speed);184- assert_relative_eq!(2.5, annotated_results[2].relative_speed);185-}186-187-#[test]188-fn test_compute_relative_speed_for_zero_times() {189- let results = vec![create_result("cmd1", 1.0), create_result("cmd2", 0.0)];190-191- let annotated_results = compute_relative_speed(&results);192-193- assert!(annotated_results.is_none());194-}195-196-pub fn tokenize(values: &str) -> Vec<String> {197- let mut tokens = vec![];198- let mut buf = String::new();199-200- let mut iter = values.chars();201- while let Some(c) = iter.next() {202- match c {203- '\\' => match iter.next() {204- Some(c2 @ ',') | Some(c2 @ '\\') => {205- buf.push(c2);206- }207- Some(c2) => {208- buf.push('\\');209- buf.push(c2);210- }211- None => buf.push('\\'),212- },213- ',' => {214- tokens.push(buf);215- buf = String::new();216- }217- _ => {218- buf.push(c);219- }220- };221- }222-223- tokens.push(buf);224-225- tokens226-}227-228-#[test]229-fn test_tokenize_single_value() {230- assert_eq!(tokenize(r""), vec![""]);231- assert_eq!(tokenize(r"foo"), vec!["foo"]);232- assert_eq!(tokenize(r" "), vec![" "]);233- assert_eq!(tokenize(r"hello\, world!"), vec!["hello, world!"]);234- assert_eq!(tokenize(r"\,"), vec![","]);235- assert_eq!(tokenize(r"\,\,\,"), vec![",,,"]);236- assert_eq!(tokenize(r"\n"), vec![r"\n"]);237- assert_eq!(tokenize(r"\\"), vec![r"\"]);238- assert_eq!(tokenize(r"\\\,"), vec![r"\,"]);239-}240-241-#[test]242-fn test_tokenize_multiple_values() {243- assert_eq!(tokenize(r"foo,bar,baz"), vec!["foo", "bar", "baz"]);244- assert_eq!(tokenize(r"hello world,foo"), vec!["hello world", "foo"]);245-246- assert_eq!(tokenize(r"hello\,world!,baz"), vec!["hello,world!", "baz"]);247-}248-249-#[test]250-fn test_tokenize_empty_values() {251- assert_eq!(tokenize(r"foo,,bar"), vec!["foo", "", "bar"]);252- assert_eq!(tokenize(r",bar"), vec!["", "bar"]);253- assert_eq!(tokenize(r"bar,"), vec!["bar", ""]);254- assert_eq!(tokenize(r",,"), vec!["", "", ""]);255-}deleted:src/hyperfine/mod.rs-16 removed
1-pub mod app;2-pub mod benchmark;3-pub mod benchmark_result;4-pub mod command;5-pub mod error;6-pub mod export;7-pub mod format;8-pub mod internal;9-pub mod options;10-pub mod outlier_detection;11-pub mod parameter_range;12-pub mod shell;13-pub mod timer;14-pub mod types;15-pub mod units;16-pub mod warnings;deleted:src/hyperfine/options.rs-107 removed
1-use super::units::{Second, Unit};2-3-#[cfg(not(windows))]4-pub const DEFAULT_SHELL: &str = "sh";5-6-#[cfg(windows)]7-pub const DEFAULT_SHELL: &str = "cmd.exe";8-9-/// Action to take when an executed command fails.10-#[derive(Debug, Clone, Copy, PartialEq)]11-pub enum CmdFailureAction {12- /// Exit with an error message13- RaiseError,14-15- /// Simply ignore the non-zero exit code16- Ignore,17-}18-19-/// Output style type option20-#[derive(Debug, Clone, Copy, PartialEq)]21-pub enum OutputStyleOption {22- /// Do not output with colors or any special formatting23- Basic,24-25- /// Output with full color and formatting26- Full,27-28- /// Keep elements such as progress bar, but use no coloring29- NoColor,30-31- /// Keep coloring, but use no progress bar32- Color,33-34- /// Disable all the output35- Disabled,36-}37-38-/// Number of runs for a benchmark39-pub struct Runs {40- /// Minimum number of benchmark runs41- pub min: u64,42-43- /// Maximum number of benchmark runs44- pub max: Option<u64>,45-}46-47-impl Default for Runs {48- fn default() -> Runs {49- Runs { min: 10, max: None }50- }51-}52-53-/// A set of options for hyperfine54-pub struct HyperfineOptions {55- /// Number of warmup runs56- pub warmup_count: u64,57-58- /// Number of benchmark runs59- pub runs: Runs,60-61- /// Minimum benchmarking time62- pub min_time_sec: Second,63-64- /// Whether or not to ignore non-zero exit codes65- pub failure_action: CmdFailureAction,66-67- /// Command to run before each timing run68- pub preparation_command: Option<Vec<String>>,69-70- /// Command to run after each benchmark71- pub cleanup_command: Option<String>,72-73- /// What color mode to use for output74- pub output_style: OutputStyleOption,75-76- /// The shell to use for executing commands.77- pub shell: String,78-79- /// Forward benchmark's stdout to hyperfine's stdout80- pub show_output: bool,81-82- /// Which time unit to use for CLI & Markdown output83- pub time_unit: Option<Unit>,84-85- /// A list of custom command names that, if defined,86- /// will be used instead of the command itself in87- /// benchmark outputs.88- pub names: Option<Vec<String>>,89-}90-91-impl Default for HyperfineOptions {92- fn default() -> HyperfineOptions {93- HyperfineOptions {94- names: None,95- warmup_count: 0,96- runs: Runs::default(),97- min_time_sec: 3.0,98- failure_action: CmdFailureAction::RaiseError,99- preparation_command: None,100- cleanup_command: None,101- output_style: OutputStyleOption::Full,102- shell: DEFAULT_SHELL.to_string(),103- show_output: false,104- time_unit: None,105- }106- }107-}deleted:src/hyperfine/outlier_detection.rs-114 removed
1-/// A module for statistical outlier detection.2-///3-/// References:4-/// - Boris Iglewicz and David Hoaglin (1993), "Volume 16: How to Detect and Handle Outliers",5-/// The ASQC Basic References in Quality Control: Statistical Techniques, Edward F. Mykytka,6-/// Ph.D., Editor.7-use statistical::median;8-9-/// Minimum modified Z-score for a datapoint to be an outlier. Here, 1.4826 is a factor that10-/// converts the MAD to an estimator for the standard deviation. The second factor is the number11-/// of standard deviations.12-pub const OUTLIER_THRESHOLD: f64 = 1.4826 * 10.0;13-14-/// Compute modifized Z-scores for a given sample. A (unmodified) Z-score is defined by15-/// `(x_i - x_mean)/x_stddev` whereas the modified Z-score is defined by `(x_i - x_median)/MAD`16-/// where MAD is the median absolute deviation.17-///18-/// References:19-/// - <https://en.wikipedia.org/wiki/Median_absolute_deviation>20-pub fn modified_zscores(xs: &[f64]) -> Vec<f64> {21- assert!(!xs.is_empty());22-23- // Compute sample median:24- let x_median = median(xs);25-26- // Compute the absolute deviations from the median:27- let deviations: Vec<f64> = xs.iter().map(|x| (x - x_median).abs()).collect();28-29- // Compute median absolute deviation:30- let mad = median(&deviations);31-32- // Handle MAD == 0 case33- let mad = if mad > 0.0 { mad } else { f64::EPSILON };34-35- // Compute modified Z-scores (x_i - x_median) / MAD36- xs.iter().map(|&x| (x - x_median) / mad).collect()37-}38-39-/// Return the number of outliers in a given sample. Outliers are defined as data points with a40-/// modified Z-score that is larger than `OUTLIER_THRESHOLD`.41-#[cfg(test)]42-pub fn num_outliers(xs: &[f64]) -> usize {43- if xs.is_empty() {44- return 0;45- }46-47- let scores = modified_zscores(xs);48- scores49- .iter()50- .filter(|&&s| s.abs() > OUTLIER_THRESHOLD)51- .count()52-}53-54-#[test]55-fn test_detect_outliers() {56- // Should not detect outliers in small samples57- assert_eq!(0, num_outliers(&[]));58- assert_eq!(0, num_outliers(&[50.0]));59- assert_eq!(0, num_outliers(&[1000.0, 0.0]));60-61- // Should not detect outliers in low-variance samples62- let xs = [-0.2, 0.0, 0.2];63- assert_eq!(0, num_outliers(&xs));64-65- // Should detect a single outlier66- let xs = [-0.2, 0.0, 0.2, 4.0];67- assert_eq!(1, num_outliers(&xs));68-69- // Should detect a single outlier70- let xs = [0.5, 0.30, 0.29, 0.31, 0.30];71- assert_eq!(1, num_outliers(&xs));72-73- // Should detect no outliers in sample drawn from normal distribution74- let xs = [75- 2.33269488,76- 1.42195907,77- -0.57527698,78- -0.31293437,79- 2.2948158,80- 0.75813273,81- -1.0712388,82- -0.96394741,83- -1.15897446,84- 1.10976285,85- ];86- assert_eq!(0, num_outliers(&xs));87-88- // Should detect two outliers that were manually added89- let xs = [90- 2.33269488,91- 1.42195907,92- -0.57527698,93- -0.31293437,94- 2.2948158,95- 0.75813273,96- -1.0712388,97- -0.96394741,98- -1.15897446,99- 1.10976285,100- 20.0,101- -500.0,102- ];103- assert_eq!(2, num_outliers(&xs));104-}105-106-#[test]107-fn test_detect_outliers_if_mad_becomes_0() {108- // See https://stats.stackexchange.com/q/339932109- let xs = [10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 100.0];110- assert_eq!(1, num_outliers(&xs));111-112- let xs = [10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 100.0, 100.0];113- assert_eq!(2, num_outliers(&xs));114-}deleted:src/hyperfine/parameter_range.rs-317 removed
1-use std::convert::TryInto;2-use std::ops::{Add, AddAssign, Div, Sub};3-use std::str::FromStr;4-5-use clap::Values;6-use rust_decimal::Decimal;7-8-use crate::hyperfine::command::Command;9-use crate::hyperfine::error::ParameterScanError;10-use crate::hyperfine::types::{NumericType, ParameterValue};11-12-trait Numeric:13- Add<Output = Self>14- + Sub<Output = Self>15- + Div<Output = Self>16- + AddAssign17- + PartialOrd18- + Copy19- + Clone20- + From<i32>21- + Into<NumericType>22-{23-}24-impl<25- T: Add<Output = Self>26- + Sub<Output = Self>27- + Div<Output = Self>28- + AddAssign29- + PartialOrd30- + Copy31- + Clone32- + From<i32>33- + Into<NumericType>,34- > Numeric for T35-{36-}37-38-#[derive(Debug)]39-struct RangeStep<T> {40- state: T,41- end: T,42- step: T,43-}44-45-impl<T: Numeric> RangeStep<T> {46- fn new(start: T, end: T, step: T) -> Result<Self, ParameterScanError> {47- if end < start {48- return Err(ParameterScanError::EmptyRange);49- }50-51- if step == T::from(0) {52- return Err(ParameterScanError::ZeroStep);53- }54-55- const MAX_PARAMETERS: usize = 100_000;56- match range_step_size_hint(start, end, step) {57- (_, Some(size)) if size <= MAX_PARAMETERS => Ok(Self {58- state: start,59- end,60- step,61- }),62- _ => Err(ParameterScanError::TooLarge),63- }64- }65-}66-67-impl<T: Numeric> Iterator for RangeStep<T> {68- type Item = T;69-70- fn next(&mut self) -> Option<Self::Item> {71- if self.state > self.end {72- return None;73- }74- let return_val = self.state;75- self.state += self.step;76-77- Some(return_val)78- }79-80- fn size_hint(&self) -> (usize, Option<usize>) {81- range_step_size_hint(self.state, self.end, self.step)82- }83-}84-85-fn range_step_size_hint<T: Numeric>(start: T, end: T, step: T) -> (usize, Option<usize>) {86- if step == T::from(0) {87- return (usize::MAX, None);88- }89-90- let steps = (end - start + T::from(1)) / step;91- steps92- .into()93- .try_into()94- .map_or((usize::MAX, None), |u| (u, Some(u)))95-}96-97-fn build_parameterized_commands<'a, T: Numeric>(98- param_min: T,99- param_max: T,100- step: T,101- command_names: Vec<&'a str>,102- command_strings: Vec<&'a str>,103- param_name: &'a str,104-) -> Result<Vec<Command<'a>>, ParameterScanError> {105- let param_range = RangeStep::new(param_min, param_max, step)?;106- let param_count = param_range.size_hint().1.unwrap();107- let command_name_count = command_names.len();108-109- // `--command-name` should appear exactly once or exactly B times,110- // where B is the total number of benchmarks.111- if command_name_count > 1 && command_name_count != param_count {112- return Err(ParameterScanError::UnexpectedCommandNameCount(113- command_name_count,114- param_count,115- ));116- }117-118- let mut i = 0;119- let mut commands = vec![];120- for value in param_range {121- for cmd in &command_strings {122- let name = command_names123- .get(i)124- .or_else(|| command_names.get(0))125- .copied();126- commands.push(Command::new_parametrized(127- name,128- cmd,129- vec![(param_name, ParameterValue::Numeric(value.into()))],130- ));131- i += 1;132- }133- }134- Ok(commands)135-}136-137-pub fn get_parameterized_commands<'a>(138- command_names: Option<Values<'a>>,139- command_strings: Values<'a>,140- mut vals: clap::Values<'a>,141- step: Option<&str>,142-) -> Result<Vec<Command<'a>>, ParameterScanError> {143- let command_names = command_names.map_or(vec![], |names| names.collect::<Vec<&str>>());144- let command_strings = command_strings.collect::<Vec<&str>>();145- let param_name = vals.next().unwrap();146- let param_min = vals.next().unwrap();147- let param_max = vals.next().unwrap();148-149- // attempt to parse as integers150- if let (Ok(param_min), Ok(param_max), Ok(step)) = (151- param_min.parse::<i32>(),152- param_max.parse::<i32>(),153- step.unwrap_or("1").parse::<i32>(),154- ) {155- return build_parameterized_commands(156- param_min,157- param_max,158- step,159- command_names,160- command_strings,161- param_name,162- );163- }164-165- // try parsing them as decimals166- let param_min = Decimal::from_str(param_min)?;167- let param_max = Decimal::from_str(param_max)?;168-169- if step.is_none() {170- return Err(ParameterScanError::StepRequired);171- }172-173- let step = Decimal::from_str(step.unwrap())?;174- build_parameterized_commands(175- param_min,176- param_max,177- step,178- command_names,179- command_strings,180- param_name,181- )182-}183-184-#[test]185-fn test_integer_range() {186- let param_range: Vec<i32> = RangeStep::new(0, 10, 3).unwrap().collect();187-188- assert_eq!(param_range.len(), 4);189- assert_eq!(param_range[0], 0);190- assert_eq!(param_range[3], 9);191-}192-193-#[test]194-fn test_decimal_range() {195- let param_min = Decimal::from(0);196- let param_max = Decimal::from(1);197- let step = Decimal::from_str("0.1").unwrap();198-199- let param_range: Vec<Decimal> = RangeStep::new(param_min, param_max, step)200- .unwrap()201- .collect();202-203- assert_eq!(param_range.len(), 11);204- assert_eq!(param_range[0], Decimal::from(0));205- assert_eq!(param_range[10], Decimal::from(1));206-}207-208-#[test]209-fn test_range_step_validate() {210- let result = RangeStep::new(0, 10, 3);211- assert!(result.is_ok());212-213- let result = RangeStep::new(214- Decimal::from(0),215- Decimal::from(1),216- Decimal::from_str("0.1").unwrap(),217- );218- assert!(result.is_ok());219-220- let result = RangeStep::new(11, 10, 1);221- assert_eq!(format!("{}", result.unwrap_err()), "Empty parameter range");222-223- let result = RangeStep::new(0, 10, 0);224- assert_eq!(225- format!("{}", result.unwrap_err()),226- "Zero is not a valid parameter step"227- );228-229- let result = RangeStep::new(0, 100_001, 1);230- assert_eq!(231- format!("{}", result.unwrap_err()),232- "Parameter range is too large"233- );234-}235-236-#[test]237-fn test_get_parameterized_commands_int() {238- let commands =239- build_parameterized_commands(1i32, 7i32, 3i32, vec![], vec!["echo {val}"], "val").unwrap();240- assert_eq!(commands.len(), 3);241- assert_eq!(commands[2].get_name(), "echo 7");242- assert_eq!(commands[2].get_shell_command(), "echo 7");243-}244-245-#[test]246-fn test_get_parameterized_commands_decimal() {247- let param_min = Decimal::from_str("0").unwrap();248- let param_max = Decimal::from_str("1").unwrap();249- let step = Decimal::from_str("0.33").unwrap();250-251- let commands = build_parameterized_commands(252- param_min,253- param_max,254- step,255- vec![],256- vec!["echo {val}"],257- "val",258- )259- .unwrap();260- assert_eq!(commands.len(), 4);261- assert_eq!(commands[3].get_name(), "echo 0.99");262- assert_eq!(commands[3].get_shell_command(), "echo 0.99");263-}264-265-#[test]266-fn test_get_parameterized_command_names() {267- let commands = build_parameterized_commands(268- 1i32,269- 3i32,270- 1i32,271- vec!["name-{val}"],272- vec!["echo {val}"],273- "val",274- )275- .unwrap();276- assert_eq!(commands.len(), 3);277- let command_names = commands278- .iter()279- .map(|c| c.get_name())280- .collect::<Vec<String>>();281- assert_eq!(command_names, vec!["name-1", "name-2", "name-3"]);282-}283-284-#[test]285-fn test_get_specified_command_names() {286- let commands = build_parameterized_commands(287- 1i32,288- 3i32,289- 1i32,290- vec!["name-a", "name-b", "name-c"],291- vec!["echo {val}"],292- "val",293- )294- .unwrap();295- assert_eq!(commands.len(), 3);296- let command_names = commands297- .iter()298- .map(|c| c.get_name())299- .collect::<Vec<String>>();300- assert_eq!(command_names, vec!["name-a", "name-b", "name-c"]);301-}302-303-#[test]304-fn test_different_command_name_count_with_parameters() {305- let result = build_parameterized_commands(306- 1i32,307- 3i32,308- 1i32,309- vec!["name-1", "name-2"],310- vec!["echo {val}"],311- "val",312- );313- assert_eq!(314- format!("{}", result.unwrap_err()),315- "'--command-name' has been specified 2 times. It has to appear exactly once, or exactly 3 times (number of benchmarks)"316- );317-}deleted:src/hyperfine/shell.rs-96 removed
1-use std::io;2-use std::process::{Command, ExitStatus, Stdio};3-4-use crate::hyperfine::timer::get_cpu_timer;5-6-/// Used to indicate the result of running a command7-#[derive(Debug, Copy, Clone)]8-pub struct ExecuteResult {9- /// The amount of user time the process used10- pub user_time: f64,11-12- /// The amount of cpu time the process used13- pub system_time: f64,14-15- /// The exit status of the process16- pub status: ExitStatus,17-}18-19-/// Execute the given command and return a timing summary20-#[cfg(windows)]21-pub fn execute_and_time(22- stdout: Stdio,23- stderr: Stdio,24- command: &str,25- shell: &str,26-) -> io::Result<ExecuteResult> {27- let mut child = run_shell_command(stdout, stderr, command, shell)?;28- let cpu_timer = get_cpu_timer(&child);29- let status = child.wait()?;30-31- let (user_time, system_time) = cpu_timer.stop();32- Ok(ExecuteResult {33- user_time,34- system_time,35- status,36- })37-}38-39-/// Execute the given command and return a timing summary40-#[cfg(not(windows))]41-pub fn execute_and_time(42- stdout: Stdio,43- stderr: Stdio,44- command: &str,45- shell: &str,46-) -> io::Result<ExecuteResult> {47- let cpu_timer = get_cpu_timer();48-49- let status = run_shell_command(stdout, stderr, command, shell)?;50-51- let (user_time, system_time) = cpu_timer.stop();52-53- Ok(ExecuteResult {54- user_time,55- system_time,56- status,57- })58-}59-60-/// Run a standard shell command using `sh -c`61-#[cfg(not(windows))]62-fn run_shell_command(63- stdout: Stdio,64- stderr: Stdio,65- command: &str,66- shell: &str,67-) -> io::Result<std::process::ExitStatus> {68- Command::new(shell)69- .arg("-c")70- .arg(command)71- .env(72- "HYPERFINE_RANDOMIZED_ENVIRONMENT_OFFSET",73- "X".repeat(rand::random::<usize>() % 4096usize),74- )75- .stdin(Stdio::null())76- .stdout(stdout)77- .stderr(stderr)78- .status()79-}80-81-/// Run a Windows shell command using `cmd.exe /C`82-#[cfg(windows)]83-fn run_shell_command(84- stdout: Stdio,85- stderr: Stdio,86- command: &str,87- shell: &str,88-) -> io::Result<std::process::Child> {89- Command::new(shell)90- .arg("/C")91- .arg(command)92- .stdin(Stdio::null())93- .stdout(stdout)94- .stderr(stderr)95- .spawn()96-}deleted:src/hyperfine/types.rs-63 removed
1-use serde::Serialize;2-use std::convert::TryFrom;3-use std::fmt;4-5-use rust_decimal::prelude::ToPrimitive;6-use rust_decimal::Decimal;7-8-#[derive(Debug, Clone, Serialize, Copy, PartialEq, Eq)]9-#[serde(untagged)]10-pub enum NumericType {11- Int(i32),12- Decimal(Decimal),13-}14-15-impl fmt::Display for NumericType {16- fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {17- match *self {18- NumericType::Int(i) => fmt::Display::fmt(&i, f),19- NumericType::Decimal(i) => fmt::Display::fmt(&i, f),20- }21- }22-}23-24-impl From<i32> for NumericType {25- fn from(x: i32) -> NumericType {26- NumericType::Int(x)27- }28-}29-30-impl From<Decimal> for NumericType {31- fn from(x: Decimal) -> NumericType {32- NumericType::Decimal(x)33- }34-}35-36-impl TryFrom<NumericType> for usize {37- type Error = ();38-39- fn try_from(numeric: NumericType) -> Result<Self, Self::Error> {40- match numeric {41- NumericType::Int(i) => usize::try_from(i).map_err(|_| ()),42- NumericType::Decimal(d) => match d.to_u64() {43- Some(u) => usize::try_from(u).map_err(|_| ()),44- None => Err(()),45- },46- }47- }48-}49-50-#[derive(Debug, Clone, PartialEq, Eq)]51-pub enum ParameterValue {52- Text(String),53- Numeric(NumericType),54-}55-56-impl<'a> ToString for ParameterValue {57- fn to_string(&self) -> String {58- match self {59- ParameterValue::Text(ref value) => value.clone(),60- ParameterValue::Numeric(value) => value.to_string(),61- }62- }63-}deleted:src/hyperfine/units.rs-45 removed
1-/// This module contains common units.2-3-pub type Scalar = f64;4-5-/// Type alias for unit of time6-pub type Second = Scalar;7-8-/// Supported time units9-#[derive(Debug, Clone, Copy, PartialEq)]10-pub enum Unit {11- Second,12- MilliSecond,13-}14-15-impl Unit {16- /// The abbreviation of the Unit.17- pub fn short_name(self) -> String {18- match self {19- Unit::Second => String::from("s"),20- Unit::MilliSecond => String::from("ms"),21- }22- }23-24- /// Returns the Second value formatted for the Unit.25- pub fn format(self, value: Second) -> String {26- match self {27- Unit::Second => format!("{:.3}", value),28- Unit::MilliSecond => format!("{:.1}", value * 1e3),29- }30- }31-}32-33-#[test]34-fn test_unit_short_name() {35- assert_eq!("s", Unit::Second.short_name());36- assert_eq!("ms", Unit::MilliSecond.short_name());37-}38-39-// Note - the values are rounded when formatted.40-#[test]41-fn test_unit_format() {42- let value: Second = 123.456789;43- assert_eq!("123.457", Unit::Second.format(value));44- assert_eq!("123456.8", Unit::MilliSecond.format(value));45-}deleted:src/hyperfine/warnings.rs-41 removed
1-use std::fmt;2-3-use crate::hyperfine::format::format_duration;4-use crate::hyperfine::internal::MIN_EXECUTION_TIME;5-use crate::hyperfine::units::Second;6-7-/// A list of all possible warnings8-pub enum Warnings {9- FastExecutionTime,10- NonZeroExitCode,11- SlowInitialRun(Second),12- OutliersDetected,13-}14-15-impl fmt::Display for Warnings {16- fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {17- match *self {18- Warnings::FastExecutionTime => write!(19- f,20- "Command took less than {:.0} ms to complete. Results might be inaccurate.",21- MIN_EXECUTION_TIME * 1e322- ),23- Warnings::NonZeroExitCode => write!(f, "Ignoring non-zero exit code."),24- Warnings::SlowInitialRun(t_first) => write!(25- f,26- "The first benchmarking run for this command was significantly slower than the \27- rest ({}). This could be caused by (filesystem) caches that were not filled until \28- after the first run. You should consider using the '--warmup' option to fill \29- those caches before the actual benchmark. Alternatively, use the '--prepare' \30- option to clear the caches before each timing run.",31- format_duration(t_first, None)32- ),33- Warnings::OutliersDetected => write!(34- f,35- "Statistical outliers were detected. Consider re-running this benchmark on a quiet \36- PC without any interferences from other programs. It might help to use the \37- '--warmup' or '--prepare' options."38- ),39- }40- }41-}added:src/timer/internal.rs+19 added
1+use crate::units::Second;2+3+#[derive(Debug, Copy, Clone)]4+pub struct CPUTimes {5+ /// Total amount of time spent executing in user mode6+ pub user_usec: i64,7+8+ /// Total amount of time spent executing in kernel mode9+ pub system_usec: i64,10+}11+12+#[derive(Debug, Copy, Clone)]13+pub struct CPUInterval {14+ /// Total amount of time spent executing in user mode15+ pub user: Second,16+17+ /// Total amount of time spent executing in kernel mode18+ pub system: Second,19+}added:src/timer/mod.rs+28 added
1+mod internal;2+3+pub mod wallclocktimer;4+5+use cfg_if::cfg_if;6+7+cfg_if! {8+ if #[cfg(windows)] {9+ mod windows_timer;10+ pub use self::windows_timer::get_cpu_timer;11+ } else {12+ mod unix_timer;13+ pub use self::unix_timer::get_cpu_timer;14+ }15+}16+use std::process::Child;17+18+/// Defines start functionality of a timer.19+pub trait TimerStart {20+ fn start() -> Self;21+ fn start_for_process(process: &Child) -> Self;22+}23+24+/// Defines stop functionality of a timer.25+pub trait TimerStop {26+ type Result;27+ fn stop(&self) -> Self::Result;28+}added:src/timer/unix_timer.rs+96 added
1+#![cfg(not(windows))]2+3+use super::internal::{CPUInterval, CPUTimes};4+use crate::timer::{TimerStart, TimerStop};5+use crate::units::Second;6+7+use std::mem;8+use std::process::Child;9+10+pub fn get_cpu_timer() -> Box<dyn TimerStop<Result = (Second, Second)>> {11+ Box::new(CPUTimer::start())12+}13+14+struct CPUTimer {15+ start_cpu: CPUTimes,16+}17+18+impl TimerStart for CPUTimer {19+ fn start() -> Self {20+ CPUTimer {21+ start_cpu: get_cpu_times(),22+ }23+ }24+25+ fn start_for_process(_: &Child) -> Self {26+ Self::start()27+ }28+}29+30+impl TimerStop for CPUTimer {31+ type Result = (Second, Second);32+33+ fn stop(&self) -> Self::Result {34+ let end_cpu = get_cpu_times();35+ let cpu_interval = cpu_time_interval(&self.start_cpu, &end_cpu);36+ (cpu_interval.user, cpu_interval.system)37+ }38+}39+40+/// Read CPU execution times ('user' and 'system')41+fn get_cpu_times() -> CPUTimes {42+ use libc::{getrusage, rusage, RUSAGE_CHILDREN};43+44+ let result: rusage = unsafe {45+ let mut buf = mem::zeroed();46+ let success = getrusage(RUSAGE_CHILDREN, &mut buf);47+ assert_eq!(0, success);48+ buf49+ };50+51+ const MICROSEC_PER_SEC: i64 = 1000 * 1000;52+53+ #[allow(clippy::useless_conversion)]54+ CPUTimes {55+ user_usec: i64::from(result.ru_utime.tv_sec) * MICROSEC_PER_SEC56+ + i64::from(result.ru_utime.tv_usec),57+ system_usec: i64::from(result.ru_stime.tv_sec) * MICROSEC_PER_SEC58+ + i64::from(result.ru_stime.tv_usec),59+ }60+}61+62+/// Compute the time intervals in between two `CPUTimes` snapshots63+fn cpu_time_interval(start: &CPUTimes, end: &CPUTimes) -> CPUInterval {64+ CPUInterval {65+ user: ((end.user_usec - start.user_usec) as f64) * 1e-6,66+ system: ((end.system_usec - start.system_usec) as f64) * 1e-6,67+ }68+}69+70+#[cfg(test)]71+use approx::assert_relative_eq;72+73+#[test]74+fn test_cpu_time_interval() {75+ let t_a = CPUTimes {76+ user_usec: 12345,77+ system_usec: 54321,78+ };79+80+ let t_b = CPUTimes {81+ user_usec: 20000,82+ system_usec: 70000,83+ };84+85+ let t_zero = cpu_time_interval(&t_a, &t_a);86+ assert!(t_zero.user.abs() < f64::EPSILON);87+ assert!(t_zero.system.abs() < f64::EPSILON);88+89+ let t_ab = cpu_time_interval(&t_a, &t_b);90+ assert_relative_eq!(0.007655, t_ab.user);91+ assert_relative_eq!(0.015679, t_ab.system);92+93+ let t_ba = cpu_time_interval(&t_b, &t_a);94+ assert_relative_eq!(-0.007655, t_ba.user);95+ assert_relative_eq!(-0.015679, t_ba.system);96+}added:src/timer/wallclocktimer.rs+30 added
1+use std::process::Child;2+use std::time::Instant;3+4+use crate::timer::{TimerStart, TimerStop};5+use crate::units::Second;6+7+pub struct WallClockTimer {8+ start: Instant,9+}10+11+impl TimerStart for WallClockTimer {12+ fn start() -> WallClockTimer {13+ WallClockTimer {14+ start: Instant::now(),15+ }16+ }17+18+ fn start_for_process(_: &Child) -> Self {19+ Self::start()20+ }21+}22+23+impl TimerStop for WallClockTimer {24+ type Result = Second;25+26+ fn stop(&self) -> Second {27+ let duration = self.start.elapsed();28+ duration.as_secs() as f64 + f64::from(duration.subsec_nanos()) * 1e-929+ }30+}added:src/timer/windows_timer.rs+83 added
1+#![cfg(windows)]2+3+use super::internal::CPUTimes;4+use crate::timer::{TimerStart, TimerStop};5+use crate::units::Second;6+7+use winapi::um::processthreadsapi::GetProcessTimes;8+use winapi::um::winnt::HANDLE;9+10+use std::mem;11+use std::os::windows::io::{AsRawHandle, RawHandle};12+use std::process::Child;13+14+const HUNDRED_NS_PER_MS: i64 = 10;15+16+pub fn get_cpu_timer(process: &Child) -> Box<dyn TimerStop<Result = (Second, Second)>> {17+ Box::new(CPUTimer::start_for_process(process))18+}19+20+struct CPUTimer {21+ handle: RawHandle,22+}23+24+impl TimerStart for CPUTimer {25+ fn start() -> Self {26+ panic!()27+ }28+29+ fn start_for_process(process: &Child) -> Self {30+ CPUTimer {31+ handle: process.as_raw_handle(),32+ }33+ }34+}35+36+impl TimerStop for CPUTimer {37+ type Result = (Second, Second);38+39+ fn stop(&self) -> Self::Result {40+ let times = get_cpu_times(self.handle);41+ (42+ times.user_usec as f64 * 1e-6,43+ times.system_usec as f64 * 1e-6,44+ )45+ }46+}47+48+/// Read CPU execution times (dummy for now)49+fn get_cpu_times(handle: RawHandle) -> CPUTimes {50+ let (user_usec, system_usec) = unsafe {51+ let mut _ctime = mem::zeroed();52+ let mut _etime = mem::zeroed();53+ let mut kernel_time = mem::zeroed();54+ let mut user_time = mem::zeroed();55+ let res = GetProcessTimes(56+ handle as HANDLE,57+ &mut _ctime,58+ &mut _etime,59+ &mut kernel_time,60+ &mut user_time,61+ );62+63+ // GetProcessTimes will exit with non-zero if success as per: https://msdn.microsoft.com/en-us/library/windows/desktop/ms683223(v=vs.85).aspx64+ if res != 0 {65+ // Extract times as laid out here: https://support.microsoft.com/en-us/help/188768/info-working-with-the-filetime-structure66+ // Both user_time and kernel_time are spans that the proces spent in either.67+ let user: i64 = (((user_time.dwHighDateTime as i64) << 32)68+ + user_time.dwLowDateTime as i64)69+ / HUNDRED_NS_PER_MS;70+ let kernel: i64 = (((kernel_time.dwHighDateTime as i64) << 32)71+ + kernel_time.dwLowDateTime as i64)72+ / HUNDRED_NS_PER_MS;73+ (user, kernel)74+ } else {75+ (0, 0)76+ }77+ };78+79+ CPUTimes {80+ user_usec,81+ system_usec,82+ }83+}added:src/app.rs+242 added
1+use atty::Stream;2+use clap::{crate_version, App, AppSettings, Arg, ArgMatches};3+use std::ffi::OsString;4+5+pub fn get_arg_matches<I, T>(args: I) -> ArgMatches<'static>6+where7+ I: IntoIterator<Item = T>,8+ T: Into<OsString> + Clone,9+{10+ let app = build_app();11+ app.get_matches_from(args)12+}13+14+/// Build the clap app for parsing command line arguments15+fn build_app() -> App<'static, 'static> {16+ let clap_color_setting = if atty::is(Stream::Stdout) {17+ AppSettings::ColoredHelp18+ } else {19+ AppSettings::ColorNever20+ };21+22+ App::new("hyperfine")23+ .version(crate_version!())24+ .setting(clap_color_setting)25+ .setting(AppSettings::DeriveDisplayOrder)26+ .setting(AppSettings::UnifiedHelpMessage)27+ .setting(AppSettings::NextLineHelp)28+ .setting(AppSettings::HidePossibleValuesInHelp)29+ .max_term_width(90)30+ .about("A command-line benchmarking tool.")31+ .arg(32+ Arg::with_name("command")33+ .help("Command to benchmark")34+ .required(true)35+ .multiple(true)36+ .empty_values(false),37+ )38+ .arg(39+ Arg::with_name("warmup")40+ .long("warmup")41+ .short("w")42+ .takes_value(true)43+ .value_name("NUM")44+ .help(45+ "Perform NUM warmup runs before the actual benchmark. This can be used \46+ to fill (disk) caches for I/O-heavy programs.",47+ ),48+ )49+ .arg(50+ Arg::with_name("min-runs")51+ .long("min-runs")52+ .short("m")53+ .takes_value(true)54+ .value_name("NUM")55+ .help("Perform at least NUM runs for each command (default: 10)."),56+ )57+ .arg(58+ Arg::with_name("max-runs")59+ .long("max-runs")60+ .short("M")61+ .takes_value(true)62+ .value_name("NUM")63+ .help("Perform at most NUM runs for each command. By default, there is no limit."),64+ )65+ .arg(66+ Arg::with_name("runs")67+ .long("runs")68+ .conflicts_with_all(&["max-runs", "min-runs"])69+ .short("r")70+ .takes_value(true)71+ .value_name("NUM")72+ .help("Perform exactly NUM runs for each command. If this option is not specified, \73+ hyperfine automatically determines the number of runs."),74+ )75+ .arg(76+ Arg::with_name("prepare")77+ .long("prepare")78+ .short("p")79+ .takes_value(true)80+ .multiple(true)81+ .number_of_values(1)82+ .value_name("CMD")83+ .help(84+ "Execute CMD before each timing run. This is useful for \85+ clearing disk caches, for example.\nThe --prepare option can \86+ be specified once for all commands or multiple times, once for \87+ each command. In the latter case, each preparation command will \88+ be run prior to the corresponding benchmark command.",89+ ),90+ )91+ .arg(92+ Arg::with_name("cleanup")93+ .long("cleanup")94+ .short("c")95+ .takes_value(true)96+ .value_name("CMD")97+ .help(98+ "Execute CMD after the completion of all benchmarking \99+ runs for each individual command to be benchmarked. \100+ This is useful if the commands to be benchmarked produce \101+ artifacts that need to be cleaned up."102+ ),103+ )104+ .arg(105+ Arg::with_name("parameter-scan")106+ .long("parameter-scan")107+ .short("P")108+ .takes_value(true)109+ .allow_hyphen_values(true)110+ .value_names(&["VAR", "MIN", "MAX"])111+ .help(112+ "Perform benchmark runs for each value in the range MIN..MAX. Replaces the \113+ string '{VAR}' in each command by the current parameter value.\n\n \114+ Example: hyperfine -P threads 1 8 'make -j {threads}'\n\n\115+ This performs benchmarks for 'make -j 1', 'make -j 2', …, 'make -j 8'.",116+ ),117+ )118+ .arg(119+ Arg::with_name("parameter-step-size")120+ .long("parameter-step-size")121+ .short("D")122+ .takes_value(true)123+ .value_names(&["DELTA"])124+ .requires("parameter-scan")125+ .help(126+ "This argument requires --parameter-scan to be specified as well. \127+ Traverse the range MIN..MAX in steps of DELTA.\n\n \128+ Example: hyperfine -P delay 0.3 0.7 -D 0.2 'sleep {delay}'\n\n\129+ This performs benchmarks for 'sleep 0.3', 'sleep 0.5' and 'sleep 0.7'.",130+ ),131+ )132+ .arg(133+ Arg::with_name("parameter-list")134+ .long("parameter-list")135+ .short("L")136+ .takes_value(true)137+ .multiple(true)138+ .allow_hyphen_values(true)139+ .value_names(&["VAR", "VALUES"])140+ .conflicts_with_all(&["parameter-scan", "parameter-step-size"])141+ .help(142+ "Perform benchmark runs for each value in the comma-separated list VALUES. \143+ Replaces the string '{VAR}' in each command by the current parameter value\144+ .\n\nExample: hyperfine -L compiler gcc,clang '{compiler} -O2 main.cpp'\n\n\145+ This performs benchmarks for 'gcc -O2 main.cpp' and 'clang -O2 main.cpp'.\n\n\146+ The option can be specified multiple times to run benchmarks for all \147+ possible parameter combinations.\n"148+ ),149+ )150+ .arg(151+ Arg::with_name("style")152+ .long("style")153+ .short("s")154+ .takes_value(true)155+ .value_name("TYPE")156+ .possible_values(&["auto", "basic", "full", "nocolor", "color", "none"])157+ .help(158+ "Set output style type (default: auto). Set this to 'basic' to disable output \159+ coloring and interactive elements. Set it to 'full' to enable all effects \160+ even if no interactive terminal was detected. Set this to 'nocolor' to \161+ keep the interactive output without any colors. Set this to 'color' to keep \162+ the colors without any interactive output. Set this to 'none' to disable all \163+ the output of the tool.",164+ ),165+ )166+ .arg(167+ Arg::with_name("shell")168+ .long("shell")169+ .short("S")170+ .takes_value(true)171+ .value_name("SHELL")172+ .overrides_with("shell")173+ .help("Set the shell to use for executing benchmarked commands."),174+ )175+ .arg(176+ Arg::with_name("ignore-failure")177+ .long("ignore-failure")178+ .short("i")179+ .help("Ignore non-zero exit codes of the benchmarked programs."),180+ )181+ .arg(182+ Arg::with_name("time-unit")183+ .long("time-unit")184+ .short("u")185+ .takes_value(true)186+ .value_name("UNIT")187+ .possible_values(&["millisecond", "second"])188+ .help("Set the time unit to be used. Possible values: millisecond, second."),189+ )190+ .arg(191+ Arg::with_name("export-asciidoc")192+ .long("export-asciidoc")193+ .takes_value(true)194+ .value_name("FILE")195+ .help("Export the timing summary statistics as an AsciiDoc table to the given FILE."),196+ )197+ .arg(198+ Arg::with_name("export-csv")199+ .long("export-csv")200+ .takes_value(true)201+ .value_name("FILE")202+ .help("Export the timing summary statistics as CSV to the given FILE. If you need \203+ the timing results for each individual run, use the JSON export format."),204+ )205+ .arg(206+ Arg::with_name("export-json")207+ .long("export-json")208+ .takes_value(true)209+ .value_name("FILE")210+ .help("Export the timing summary statistics and timings of individual runs as JSON to the given FILE."),211+ )212+ .arg(213+ Arg::with_name("export-markdown")214+ .long("export-markdown")215+ .takes_value(true)216+ .value_name("FILE")217+ .help("Export the timing summary statistics as a Markdown table to the given FILE."),218+ )219+ .arg(220+ Arg::with_name("show-output")221+ .long("show-output")222+ .conflicts_with("style")223+ .help(224+ "Print the stdout and stderr of the benchmark instead of suppressing it. \225+ This will increase the time it takes for benchmarks to run, \226+ so it should only be used for debugging purposes or \227+ when trying to benchmark output speed.",228+ ),229+ )230+ .arg(231+ Arg::with_name("command-name")232+ .long("command-name")233+ .short("n")234+ .takes_value(true)235+ .multiple(true)236+ .number_of_values(1)237+ .value_name("NAME")238+ .help("Give a meaningful name to a command"),239+ )240+ .help_message("Print this help message.")241+ .version_message("Show version information.")242+}added:src/benchmark_result.rs+77 added
1+use serde::Serialize;2+use std::collections::BTreeMap;3+4+use crate::units::Second;5+6+/// Set of values that will be exported.7+// NOTE: `serde` is used for JSON serialization, but not for CSV serialization due to the8+// `parameters` map. Update `src/hyperfine/export/csv.rs` with new fields, as appropriate.9+#[derive(Debug, Default, Clone, Serialize, PartialEq)]10+pub struct BenchmarkResult {11+ /// The command that was run12+ pub command: String,13+14+ /// The mean run time15+ pub mean: Second,16+17+ /// The standard deviation of all run times18+ pub stddev: Second,19+20+ /// The median run time21+ pub median: Second,22+23+ /// Time spend in user space24+ pub user: Second,25+26+ /// Time spent in system space27+ pub system: Second,28+29+ /// Min time measured30+ pub min: Second,31+32+ /// Max time measured33+ pub max: Second,34+35+ /// All run time measurements36+ #[serde(skip_serializing_if = "Option::is_none")]37+ pub times: Option<Vec<Second>>,38+39+ /// All run exit codes40+ pub exit_codes: Vec<Option<i32>>,41+42+ /// Any parameter values used43+ #[serde(skip_serializing_if = "BTreeMap::is_empty")]44+ pub parameters: BTreeMap<String, String>,45+}46+47+impl BenchmarkResult {48+ /// Create a new entry with the given values.49+ #[allow(clippy::too_many_arguments)]50+ pub fn new(51+ command: String,52+ mean: Second,53+ stddev: Second,54+ median: Second,55+ user: Second,56+ system: Second,57+ min: Second,58+ max: Second,59+ times: Vec<Second>,60+ exit_codes: Vec<Option<i32>>,61+ parameters: BTreeMap<String, String>,62+ ) -> Self {63+ BenchmarkResult {64+ command,65+ mean,66+ stddev,67+ median,68+ user,69+ system,70+ min,71+ max,72+ times: Some(times),73+ exit_codes,74+ parameters,75+ }76+ }77+}added:src/benchmark.rs+484 added
1+use std::cmp;2+use std::io;3+use std::process::{ExitStatus, Stdio};4+5+use colored::*;6+use statistical::{mean, median, standard_deviation};7+8+use crate::benchmark_result::BenchmarkResult;9+use crate::command::Command;10+use crate::format::{format_duration, format_duration_unit};11+use crate::internal::{get_progress_bar, max, min, MIN_EXECUTION_TIME};12+use crate::options::{CmdFailureAction, HyperfineOptions, OutputStyleOption};13+use crate::outlier_detection::{modified_zscores, OUTLIER_THRESHOLD};14+use crate::shell::execute_and_time;15+use crate::timer::wallclocktimer::WallClockTimer;16+use crate::timer::{TimerStart, TimerStop};17+use crate::units::Second;18+use crate::warnings::Warnings;19+20+/// Results from timing a single shell command21+#[derive(Debug, Default, Copy, Clone)]22+pub struct TimingResult {23+ /// Wall clock time24+ pub time_real: Second,25+26+ /// Time spent in user mode27+ pub time_user: Second,28+29+ /// Time spent in kernel mode30+ pub time_system: Second,31+}32+33+/// Correct for shell spawning time34+fn subtract_shell_spawning_time(time: Second, shell_spawning_time: Second) -> Second {35+ if time < shell_spawning_time {36+ 0.037+ } else {38+ time - shell_spawning_time39+ }40+}41+42+/// Run the given shell command and measure the execution time43+pub fn time_shell_command(44+ shell: &str,45+ command: &Command<'_>,46+ show_output: bool,47+ failure_action: CmdFailureAction,48+ shell_spawning_time: Option<TimingResult>,49+) -> io::Result<(TimingResult, ExitStatus)> {50+ let (stdout, stderr) = if show_output {51+ (Stdio::inherit(), Stdio::inherit())52+ } else {53+ (Stdio::null(), Stdio::null())54+ };55+56+ let wallclock_timer = WallClockTimer::start();57+ let result = execute_and_time(stdout, stderr, &command.get_shell_command(), shell)?;58+ let mut time_real = wallclock_timer.stop();59+60+ let mut time_user = result.user_time;61+ let mut time_system = result.system_time;62+63+ if failure_action == CmdFailureAction::RaiseError && !result.status.success() {64+ return Err(io::Error::new(65+ io::ErrorKind::Other,66+ format!(67+ "{}. \68+ Use the '-i'/'--ignore-failure' option if you want to ignore this. \69+ Alternatively, use the '--show-output' option to debug what went wrong.",70+ result.status.code().map_or(71+ "The process has been terminated by a signal".into(),72+ |c| format!("Command terminated with non-zero exit code: {}", c)73+ )74+ ),75+ ));76+ }77+78+ // Correct for shell spawning time79+ if let Some(spawning_time) = shell_spawning_time {80+ time_real = subtract_shell_spawning_time(time_real, spawning_time.time_real);81+ time_user = subtract_shell_spawning_time(time_user, spawning_time.time_user);82+ time_system = subtract_shell_spawning_time(time_system, spawning_time.time_system);83+ }84+85+ Ok((86+ TimingResult {87+ time_real,88+ time_user,89+ time_system,90+ },91+ result.status,92+ ))93+}94+95+/// Measure the average shell spawning time96+pub fn mean_shell_spawning_time(97+ shell: &str,98+ style: OutputStyleOption,99+ show_output: bool,100+) -> io::Result<TimingResult> {101+ const COUNT: u64 = 50;102+ let progress_bar = if style != OutputStyleOption::Disabled {103+ Some(get_progress_bar(104+ COUNT,105+ "Measuring shell spawning time",106+ style,107+ ))108+ } else {109+ None110+ };111+112+ let mut times_real: Vec<Second> = vec![];113+ let mut times_user: Vec<Second> = vec![];114+ let mut times_system: Vec<Second> = vec![];115+116+ for _ in 0..COUNT {117+ // Just run the shell without any command118+ let res = time_shell_command(119+ shell,120+ &Command::new(None, ""),121+ show_output,122+ CmdFailureAction::RaiseError,123+ None,124+ );125+126+ match res {127+ Err(_) => {128+ let shell_cmd = if cfg!(windows) {129+ format!("{} /C \"\"", shell)130+ } else {131+ format!("{} -c \"\"", shell)132+ };133+134+ return Err(io::Error::new(135+ io::ErrorKind::Other,136+ format!(137+ "Could not measure shell execution time. \138+ Make sure you can run '{}'.",139+ shell_cmd140+ ),141+ ));142+ }143+ Ok((r, _)) => {144+ times_real.push(r.time_real);145+ times_user.push(r.time_user);146+ times_system.push(r.time_system);147+ }148+ }149+150+ if let Some(bar) = progress_bar.as_ref() {151+ bar.inc(1)152+ }153+ }154+155+ if let Some(bar) = progress_bar.as_ref() {156+ bar.finish_and_clear()157+ }158+159+ Ok(TimingResult {160+ time_real: mean(×_real),161+ time_user: mean(×_user),162+ time_system: mean(×_system),163+ })164+}165+166+fn run_intermediate_command(167+ shell: &str,168+ command: &Option<Command<'_>>,169+ show_output: bool,170+ error_output: &'static str,171+) -> io::Result<TimingResult> {172+ if let Some(ref cmd) = command {173+ let res = time_shell_command(shell, cmd, show_output, CmdFailureAction::RaiseError, None);174+ if res.is_err() {175+ return Err(io::Error::new(io::ErrorKind::Other, error_output));176+ }177+ return res.map(|r| r.0);178+ }179+ Ok(TimingResult {180+ ..Default::default()181+ })182+}183+184+/// Run the command specified by `--prepare`.185+fn run_preparation_command(186+ shell: &str,187+ command: &Option<Command<'_>>,188+ show_output: bool,189+) -> io::Result<TimingResult> {190+ let error_output = "The preparation command terminated with a non-zero exit code. \191+ Append ' || true' to the command if you are sure that this can be ignored.";192+193+ run_intermediate_command(shell, command, show_output, error_output)194+}195+196+/// Run the command specified by `--cleanup`.197+fn run_cleanup_command(198+ shell: &str,199+ command: &Option<Command<'_>>,200+ show_output: bool,201+) -> io::Result<TimingResult> {202+ let error_output = "The cleanup command terminated with a non-zero exit code. \203+ Append ' || true' to the command if you are sure that this can be ignored.";204+205+ run_intermediate_command(shell, command, show_output, error_output)206+}207+208+#[cfg(unix)]209+fn extract_exit_code(status: ExitStatus) -> Option<i32> {210+ use std::os::unix::process::ExitStatusExt;211+212+ /* From the ExitStatus::code documentation:213+ "On Unix, this will return None if the process was terminated by a signal."214+ In that case, ExitStatusExt::signal should never return None.215+ */216+ status.code().or_else(||217+ /* To differentiate between "normal" exit codes and signals, we are using218+ something similar to bash exit codes (https://tldp.org/LDP/abs/html/exitcodes.html)219+ by adding 128 to a signal integer value.220+ */221+ status.signal().map(|s| 128 + s))222+}223+224+#[cfg(not(unix))]225+fn extract_exit_code(status: ExitStatus) -> Option<i32> {226+ status.code()227+}228+229+/// Run the benchmark for a single shell command230+pub fn run_benchmark(231+ num: usize,232+ cmd: &Command<'_>,233+ shell_spawning_time: TimingResult,234+ options: &HyperfineOptions,235+) -> io::Result<BenchmarkResult> {236+ let command_name = cmd.get_name();237+ if options.output_style != OutputStyleOption::Disabled {238+ println!(239+ "{}{}: {}",240+ "Benchmark ".bold(),241+ (num + 1).to_string().bold(),242+ command_name,243+ );244+ }245+246+ let mut times_real: Vec<Second> = vec![];247+ let mut times_user: Vec<Second> = vec![];248+ let mut times_system: Vec<Second> = vec![];249+ let mut exit_codes: Vec<Option<i32>> = vec![];250+ let mut all_succeeded = true;251+252+ // Run init command253+ let prepare_cmd = options.preparation_command.as_ref().map(|values| {254+ let preparation_command = if values.len() == 1 {255+ &values[0]256+ } else {257+ &values[num]258+ };259+ Command::new_parametrized(None, preparation_command, cmd.get_parameters().clone())260+ });261+262+ // Warmup phase263+ if options.warmup_count > 0 {264+ let progress_bar = if options.output_style != OutputStyleOption::Disabled {265+ Some(get_progress_bar(266+ options.warmup_count,267+ "Performing warmup runs",268+ options.output_style,269+ ))270+ } else {271+ None272+ };273+274+ for _ in 0..options.warmup_count {275+ let _ = run_preparation_command(&options.shell, &prepare_cmd, options.show_output)?;276+ let _ = time_shell_command(277+ &options.shell,278+ cmd,279+ options.show_output,280+ options.failure_action,281+ None,282+ )?;283+ if let Some(bar) = progress_bar.as_ref() {284+ bar.inc(1)285+ }286+ }287+ if let Some(bar) = progress_bar.as_ref() {288+ bar.finish_and_clear()289+ }290+ }291+292+ // Set up progress bar (and spinner for initial measurement)293+ let progress_bar = if options.output_style != OutputStyleOption::Disabled {294+ Some(get_progress_bar(295+ options.runs.min,296+ "Initial time measurement",297+ options.output_style,298+ ))299+ } else {300+ None301+ };302+303+ let prepare_res = run_preparation_command(&options.shell, &prepare_cmd, options.show_output)?;304+305+ // Initial timing run306+ let (res, status) = time_shell_command(307+ &options.shell,308+ cmd,309+ options.show_output,310+ options.failure_action,311+ Some(shell_spawning_time),312+ )?;313+ let success = status.success();314+315+ // Determine number of benchmark runs316+ let runs_in_min_time = (options.min_time_sec317+ / (res.time_real + prepare_res.time_real + shell_spawning_time.time_real))318+ as u64;319+320+ let count = {321+ let min = cmp::max(runs_in_min_time, options.runs.min);322+323+ options324+ .runs325+ .max326+ .as_ref()327+ .map(|max| cmp::min(min, *max))328+ .unwrap_or(min)329+ };330+331+ let count_remaining = count - 1;332+333+ // Save the first result334+ times_real.push(res.time_real);335+ times_user.push(res.time_user);336+ times_system.push(res.time_system);337+ exit_codes.push(extract_exit_code(status));338+339+ all_succeeded = all_succeeded && success;340+341+ // Re-configure the progress bar342+ if let Some(bar) = progress_bar.as_ref() {343+ bar.set_length(count)344+ }345+ if let Some(bar) = progress_bar.as_ref() {346+ bar.inc(1)347+ }348+349+ // Gather statistics350+ for _ in 0..count_remaining {351+ run_preparation_command(&options.shell, &prepare_cmd, options.show_output)?;352+353+ let msg = {354+ let mean = format_duration(mean(×_real), options.time_unit);355+ format!("Current estimate: {}", mean.to_string().green())356+ };357+358+ if let Some(bar) = progress_bar.as_ref() {359+ bar.set_message(msg.to_owned())360+ }361+362+ let (res, status) = time_shell_command(363+ &options.shell,364+ cmd,365+ options.show_output,366+ options.failure_action,367+ Some(shell_spawning_time),368+ )?;369+ let success = status.success();370+371+ times_real.push(res.time_real);372+ times_user.push(res.time_user);373+ times_system.push(res.time_system);374+ exit_codes.push(extract_exit_code(status));375+376+ all_succeeded = all_succeeded && success;377+378+ if let Some(bar) = progress_bar.as_ref() {379+ bar.inc(1)380+ }381+ }382+383+ if let Some(bar) = progress_bar.as_ref() {384+ bar.finish_and_clear()385+ }386+387+ // Compute statistical quantities388+ let t_num = times_real.len();389+ let t_mean = mean(×_real);390+ let t_stddev = standard_deviation(×_real, Some(t_mean));391+ let t_median = median(×_real);392+ let t_min = min(×_real);393+ let t_max = max(×_real);394+395+ let user_mean = mean(×_user);396+ let system_mean = mean(×_system);397+398+ // Formatting and console output399+ let (mean_str, time_unit) = format_duration_unit(t_mean, options.time_unit);400+ let stddev_str = format_duration(t_stddev, Some(time_unit));401+ let min_str = format_duration(t_min, Some(time_unit));402+ let max_str = format_duration(t_max, Some(time_unit));403+ let num_str = format!("{} runs", t_num);404+405+ let user_str = format_duration(user_mean, Some(time_unit));406+ let system_str = format_duration(system_mean, Some(time_unit));407+408+ if options.output_style != OutputStyleOption::Disabled {409+ println!(410+ " Time ({} ± {}): {:>8} ± {:>8} [User: {}, System: {}]",411+ "mean".green().bold(),412+ "σ".green(),413+ mean_str.green().bold(),414+ stddev_str.green(),415+ user_str.blue(),416+ system_str.blue()417+ );418+419+ println!(420+ " Range ({} … {}): {:>8} … {:>8} {}",421+ "min".cyan(),422+ "max".purple(),423+ min_str.cyan(),424+ max_str.purple(),425+ num_str.dimmed()426+ );427+ }428+429+ // Warnings430+ let mut warnings = vec![];431+432+ // Check execution time433+ if times_real.iter().any(|&t| t < MIN_EXECUTION_TIME) {434+ warnings.push(Warnings::FastExecutionTime);435+ }436+437+ // Check programm exit codes438+ if !all_succeeded {439+ warnings.push(Warnings::NonZeroExitCode);440+ }441+442+ // Run outlier detection443+ let scores = modified_zscores(×_real);444+ if scores[0] > OUTLIER_THRESHOLD {445+ warnings.push(Warnings::SlowInitialRun(times_real[0]));446+ } else if scores.iter().any(|&s| s.abs() > OUTLIER_THRESHOLD) {447+ warnings.push(Warnings::OutliersDetected);448+ }449+450+ if !warnings.is_empty() {451+ eprintln!(" ");452+453+ for warning in &warnings {454+ eprintln!(" {}: {}", "Warning".yellow(), warning);455+ }456+ }457+458+ if options.output_style != OutputStyleOption::Disabled {459+ println!(" ");460+ }461+462+ // Run cleanup command463+ let cleanup_cmd = options.cleanup_command.as_ref().map(|cleanup_command| {464+ Command::new_parametrized(None, cleanup_command, cmd.get_parameters().clone())465+ });466+ run_cleanup_command(&options.shell, &cleanup_cmd, options.show_output)?;467+468+ Ok(BenchmarkResult::new(469+ command_name,470+ t_mean,471+ t_stddev,472+ t_median,473+ user_mean,474+ system_mean,475+ t_min,476+ t_max,477+ times_real,478+ exit_codes,479+ cmd.get_parameters()480+ .iter()481+ .map(|(name, value)| ((*name).to_string(), value.to_string()))482+ .collect(),483+ ))484+}added:src/command.rs+115 added
1+use std::collections::BTreeMap;2+use std::fmt;3+4+use super::types::ParameterValue;5+6+/// A command that should be benchmarked.7+#[derive(Debug, Clone, PartialEq, Eq)]8+pub struct Command<'a> {9+ /// The command name (without parameter substitution)10+ name: Option<&'a str>,11+12+ /// The command that should be executed (without parameter substitution)13+ expression: &'a str,14+15+ /// Zero or more parameter values.16+ parameters: Vec<(&'a str, ParameterValue)>,17+}18+19+impl<'a> Command<'a> {20+ pub fn new(name: Option<&'a str>, expression: &'a str) -> Command<'a> {21+ Command {22+ name,23+ expression,24+ parameters: Vec::new(),25+ }26+ }27+28+ pub fn new_parametrized(29+ name: Option<&'a str>,30+ expression: &'a str,31+ parameters: Vec<(&'a str, ParameterValue)>,32+ ) -> Command<'a> {33+ Command {34+ name,35+ expression,36+ parameters,37+ }38+ }39+40+ pub fn get_name(&self) -> String {41+ self.name.map_or_else(42+ || self.get_shell_command(),43+ |name| self.replace_parameters_in(name),44+ )45+ }46+47+ pub fn get_shell_command(&self) -> String {48+ self.replace_parameters_in(self.expression)49+ }50+51+ pub fn get_parameters(&self) -> &Vec<(&'a str, ParameterValue)> {52+ &self.parameters53+ }54+55+ fn replace_parameters_in(&self, original: &str) -> String {56+ let mut result = String::new();57+ let mut replacements = BTreeMap::<String, String>::new();58+ for (param_name, param_value) in &self.parameters {59+ replacements.insert(60+ format!("{{{param_name}}}", param_name = param_name),61+ param_value.to_string(),62+ );63+ }64+ let mut remaining = original;65+ // Manually replace consecutive occurrences to avoid double-replacing: e.g.,66+ //67+ // hyperfine -L foo 'a,{bar}' -L bar 'baz,quux' 'echo {foo} {bar}'68+ //69+ // should not ever run 'echo baz baz'. See `test_get_shell_command_nonoverlapping`.70+ 'outer: while let Some(head) = remaining.chars().next() {71+ for (k, v) in &replacements {72+ if remaining.starts_with(k.as_str()) {73+ result.push_str(v);74+ remaining = &remaining[k.len()..];75+ continue 'outer;76+ }77+ }78+ result.push(head);79+ remaining = &remaining[head.len_utf8()..];80+ }81+ result82+ }83+}84+85+#[test]86+fn test_get_shell_command_nonoverlapping() {87+ let cmd = Command::new_parametrized(88+ None,89+ "echo {foo} {bar}",90+ vec![91+ ("foo", ParameterValue::Text("{bar} baz".into())),92+ ("bar", ParameterValue::Text("quux".into())),93+ ],94+ );95+ assert_eq!(cmd.get_shell_command(), "echo {bar} baz quux");96+}97+98+#[test]99+fn test_get_parameterized_command_name() {100+ let cmd = Command::new_parametrized(101+ Some("name-{bar}-{foo}"),102+ "echo {foo} {bar}",103+ vec![104+ ("foo", ParameterValue::Text("baz".into())),105+ ("bar", ParameterValue::Text("quux".into())),106+ ],107+ );108+ assert_eq!(cmd.get_name(), "name-quux-baz");109+}110+111+impl<'a> fmt::Display for Command<'a> {112+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {113+ write!(f, "{}", self.get_shell_command())114+ }115+}added:src/error.rs+91 added
1+use rust_decimal::Error as DecimalError;2+use std::error::Error;3+use std::fmt;4+use std::num;5+use std::num::ParseIntError;6+7+#[derive(Debug)]8+pub enum ParameterScanError {9+ ParseIntError(num::ParseIntError),10+ ParseDecimalError(DecimalError),11+ EmptyRange,12+ TooLarge,13+ ZeroStep,14+ StepRequired,15+ UnexpectedCommandNameCount(usize, usize),16+}17+18+impl From<num::ParseIntError> for ParameterScanError {19+ fn from(e: num::ParseIntError) -> ParameterScanError {20+ ParameterScanError::ParseIntError(e)21+ }22+}23+24+impl From<DecimalError> for ParameterScanError {25+ fn from(e: DecimalError) -> ParameterScanError {26+ ParameterScanError::ParseDecimalError(e)27+ }28+}29+30+impl fmt::Display for ParameterScanError {31+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {32+ match *self {33+ ParameterScanError::ParseIntError(ref e) => write!(f, "{}", e),34+ ParameterScanError::ParseDecimalError(ref e) => write!(f, "{}", e),35+ ParameterScanError::EmptyRange => write!(f, "Empty parameter range"),36+ ParameterScanError::TooLarge => write!(f, "Parameter range is too large"),37+ ParameterScanError::ZeroStep => write!(f, "Zero is not a valid parameter step"),38+ ParameterScanError::StepRequired => write!(39+ f,40+ "A step size is required when the range bounds are \41+ floating point numbers. The step size can be specified \42+ with the '--parameter-step-size' parameter"43+ ),44+ ParameterScanError::UnexpectedCommandNameCount(real, expected) => {45+ write!(46+ f,47+ "'--command-name' has been specified {} times. It has to appear exactly once, or exactly {} times (number of benchmarks)",48+ real, expected49+ )50+ }51+ }52+ }53+}54+55+impl Error for ParameterScanError {}56+57+#[derive(Debug)]58+pub enum OptionsError<'a> {59+ RunsBelowTwo,60+ EmptyRunsRange,61+ TooManyCommandNames(usize),62+ UnexpectedCommandNameCount(usize, usize),63+ NumericParsingError(&'a str, ParseIntError),64+}65+66+impl<'a> fmt::Display for OptionsError<'a> {67+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {68+ match *self {69+ OptionsError::EmptyRunsRange => write!(f, "Empty runs range"),70+ OptionsError::RunsBelowTwo => write!(f, "Number of runs below two"),71+ OptionsError::TooManyCommandNames(n) => {72+ write!(f, "Too many --command-name options: expected {} at most", n)73+ }74+ OptionsError::UnexpectedCommandNameCount(real, expected) => {75+ write!(76+ f,77+ "'--command-name' has been specified {} times. It has to appear exactly once, or exactly {} times (number of benchmarks)",78+ real, expected79+ )80+ }81+ OptionsError::NumericParsingError(cmd, ref err) => write!(82+ f,83+ "Could not read numeric argument to '--{cmd}': {err}",84+ cmd = cmd,85+ err = err86+ ),87+ }88+ }89+}90+91+impl<'a> Error for OptionsError<'a> {}added:src/format.rs+65 added
1+use crate::units::{Second, Unit};2+3+/// Format the given duration as a string. The output-unit can be enforced by setting `unit` to4+/// `Some(target_unit)`. If `unit` is `None`, it will be determined automatically.5+pub fn format_duration(duration: Second, unit: Option<Unit>) -> String {6+ let (duration_fmt, _) = format_duration_unit(duration, unit);7+ duration_fmt8+}9+10+/// Like `format_duration`, but returns the target unit as well.11+pub fn format_duration_unit(duration: Second, unit: Option<Unit>) -> (String, Unit) {12+ let (out_str, out_unit) = format_duration_value(duration, unit);13+14+ (format!("{} {}", out_str, out_unit.short_name()), out_unit)15+}16+17+/// Like `format_duration`, but returns the target unit as well.18+pub fn format_duration_value(duration: Second, unit: Option<Unit>) -> (String, Unit) {19+ if (duration < 1.0 && unit.is_none()) || unit == Some(Unit::MilliSecond) {20+ (Unit::MilliSecond.format(duration), Unit::MilliSecond)21+ } else {22+ (Unit::Second.format(duration), Unit::Second)23+ }24+}25+26+#[test]27+fn test_format_duration_unit_basic() {28+ let (out_str, out_unit) = format_duration_unit(1.3, None);29+30+ assert_eq!("1.300 s", out_str);31+ assert_eq!(Unit::Second, out_unit);32+33+ let (out_str, out_unit) = format_duration_unit(1.0, None);34+35+ assert_eq!("1.000 s", out_str);36+ assert_eq!(Unit::Second, out_unit);37+38+ let (out_str, out_unit) = format_duration_unit(0.999, None);39+40+ assert_eq!("999.0 ms", out_str);41+ assert_eq!(Unit::MilliSecond, out_unit);42+43+ let (out_str, out_unit) = format_duration_unit(0.0, None);44+45+ assert_eq!("0.0 ms", out_str);46+ assert_eq!(Unit::MilliSecond, out_unit);47+48+ let (out_str, out_unit) = format_duration_unit(1000.0, None);49+50+ assert_eq!("1000.000 s", out_str);51+ assert_eq!(Unit::Second, out_unit);52+}53+54+#[test]55+fn test_format_duration_unit_with_unit() {56+ let (out_str, out_unit) = format_duration_unit(1.3, Some(Unit::Second));57+58+ assert_eq!("1.300 s", out_str);59+ assert_eq!(Unit::Second, out_unit);60+61+ let (out_str, out_unit) = format_duration_unit(1.3, Some(Unit::MilliSecond));62+63+ assert_eq!("1300.0 ms", out_str);64+ assert_eq!(Unit::MilliSecond, out_unit);65+}added:src/internal.rs+255 added
1+use colored::*;2+use indicatif::{ProgressBar, ProgressStyle};3+4+use crate::benchmark_result::BenchmarkResult;5+use crate::options::OutputStyleOption;6+use crate::units::{Scalar, Second};7+8+use std::cmp::Ordering;9+use std::iter::Iterator;10+11+/// Threshold for warning about fast execution time12+pub const MIN_EXECUTION_TIME: Second = 5e-3;13+14+#[cfg(not(windows))]15+const TICK_SETTINGS: (&str, u64) = ("⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏ ", 80);16+17+#[cfg(windows)]18+const TICK_SETTINGS: (&str, u64) = (r"+-x| ", 200);19+20+/// Return a pre-configured progress bar21+pub fn get_progress_bar(length: u64, msg: &str, option: OutputStyleOption) -> ProgressBar {22+ let progressbar_style = match option {23+ OutputStyleOption::Basic | OutputStyleOption::Color => ProgressStyle::default_bar(),24+ _ => ProgressStyle::default_spinner()25+ .tick_chars(TICK_SETTINGS.0)26+ .template(" {spinner} {msg:<30} {wide_bar} ETA {eta_precise}"),27+ };28+29+ let progress_bar = match option {30+ OutputStyleOption::Basic | OutputStyleOption::Color => ProgressBar::hidden(),31+ _ => ProgressBar::new(length),32+ };33+ progress_bar.set_style(progressbar_style);34+ progress_bar.enable_steady_tick(TICK_SETTINGS.1);35+ progress_bar.set_message(msg.to_owned());36+37+ progress_bar38+}39+40+/// A max function for f64's without NaNs41+pub fn max(vals: &[f64]) -> f64 {42+ *vals43+ .iter()44+ .max_by(|a, b| a.partial_cmp(b).unwrap())45+ .unwrap()46+}47+48+/// A min function for f64's without NaNs49+pub fn min(vals: &[f64]) -> f64 {50+ *vals51+ .iter()52+ .min_by(|a, b| a.partial_cmp(b).unwrap())53+ .unwrap()54+}55+56+#[derive(Debug)]57+pub struct BenchmarkResultWithRelativeSpeed<'a> {58+ pub result: &'a BenchmarkResult,59+ pub relative_speed: Scalar,60+ pub relative_speed_stddev: Scalar,61+ pub is_fastest: bool,62+}63+64+fn compare_mean_time(l: &BenchmarkResult, r: &BenchmarkResult) -> Ordering {65+ l.mean.partial_cmp(&r.mean).unwrap_or(Ordering::Equal)66+}67+68+pub fn compute_relative_speed(69+ results: &[BenchmarkResult],70+) -> Option<Vec<BenchmarkResultWithRelativeSpeed>> {71+ let fastest: &BenchmarkResult = results72+ .iter()73+ .min_by(|&l, &r| compare_mean_time(l, r))74+ .expect("at least one benchmark result");75+76+ if fastest.mean == 0.0 {77+ return None;78+ }79+80+ Some(81+ results82+ .iter()83+ .map(|result| {84+ let ratio = result.mean / fastest.mean;85+86+ // https://en.wikipedia.org/wiki/Propagation_of_uncertainty#Example_formulas87+ // Covariance asssumed to be 0, i.e. variables are assumed to be independent88+ let ratio_stddev = ratio89+ * ((result.stddev / result.mean).powi(2)90+ + (fastest.stddev / fastest.mean).powi(2))91+ .sqrt();92+93+ BenchmarkResultWithRelativeSpeed {94+ result,95+ relative_speed: ratio,96+ relative_speed_stddev: ratio_stddev,97+ is_fastest: result == fastest,98+ }99+ })100+ .collect(),101+ )102+}103+104+pub fn write_benchmark_comparison(results: &[BenchmarkResult]) {105+ if results.len() < 2 {106+ return;107+ }108+109+ if let Some(mut annotated_results) = compute_relative_speed(results) {110+ annotated_results.sort_by(|l, r| compare_mean_time(l.result, r.result));111+112+ let fastest = &annotated_results[0];113+ let others = &annotated_results[1..];114+115+ println!("{}", "Summary".bold());116+ println!(" '{}' ran", fastest.result.command.cyan());117+118+ for item in others {119+ println!(120+ "{} ± {} times faster than '{}'",121+ format!("{:8.2}", item.relative_speed).bold().green(),122+ format!("{:.2}", item.relative_speed_stddev).green(),123+ &item.result.command.magenta()124+ );125+ }126+ } else {127+ eprintln!(128+ "{}: The benchmark comparison could not be computed as some benchmark times are zero. \129+ This could be caused by background interference during the initial calibration phase \130+ of hyperfine, in combination with very fast commands (faster than a few milliseconds). \131+ Try to re-run the benchmark on a quiet system. If it does not help, you command is \132+ most likely too fast to be accurately benchmarked by hyperfine.",133+ "Note".bold().red()134+ );135+ }136+}137+138+#[test]139+fn test_max() {140+ let assert_float_eq = |a, b| {141+ assert!((a - b) < f64::EPSILON);142+ };143+144+ assert_float_eq(1.0, max(&[1.0]));145+ assert_float_eq(-1.0, max(&[-1.0]));146+ assert_float_eq(-1.0, max(&[-2.0, -1.0]));147+ assert_float_eq(1.0, max(&[-1.0, 1.0]));148+ assert_float_eq(1.0, max(&[-1.0, 1.0, 0.0]));149+}150+151+#[cfg(test)]152+fn create_result(name: &str, mean: Scalar) -> BenchmarkResult {153+ use std::collections::BTreeMap;154+155+ BenchmarkResult {156+ command: name.into(),157+ mean,158+ stddev: 1.0,159+ median: mean,160+ user: mean,161+ system: 0.0,162+ min: mean,163+ max: mean,164+ times: None,165+ exit_codes: Vec::new(),166+ parameters: BTreeMap::new(),167+ }168+}169+170+#[test]171+fn test_compute_relative_speed() {172+ use approx::assert_relative_eq;173+174+ let results = vec![175+ create_result("cmd1", 3.0),176+ create_result("cmd2", 2.0),177+ create_result("cmd3", 5.0),178+ ];179+180+ let annotated_results = compute_relative_speed(&results).unwrap();181+182+ assert_relative_eq!(1.5, annotated_results[0].relative_speed);183+ assert_relative_eq!(1.0, annotated_results[1].relative_speed);184+ assert_relative_eq!(2.5, annotated_results[2].relative_speed);185+}186+187+#[test]188+fn test_compute_relative_speed_for_zero_times() {189+ let results = vec![create_result("cmd1", 1.0), create_result("cmd2", 0.0)];190+191+ let annotated_results = compute_relative_speed(&results);192+193+ assert!(annotated_results.is_none());194+}195+196+pub fn tokenize(values: &str) -> Vec<String> {197+ let mut tokens = vec![];198+ let mut buf = String::new();199+200+ let mut iter = values.chars();201+ while let Some(c) = iter.next() {202+ match c {203+ '\\' => match iter.next() {204+ Some(c2 @ ',') | Some(c2 @ '\\') => {205+ buf.push(c2);206+ }207+ Some(c2) => {208+ buf.push('\\');209+ buf.push(c2);210+ }211+ None => buf.push('\\'),212+ },213+ ',' => {214+ tokens.push(buf);215+ buf = String::new();216+ }217+ _ => {218+ buf.push(c);219+ }220+ };221+ }222+223+ tokens.push(buf);224+225+ tokens226+}227+228+#[test]229+fn test_tokenize_single_value() {230+ assert_eq!(tokenize(r""), vec![""]);231+ assert_eq!(tokenize(r"foo"), vec!["foo"]);232+ assert_eq!(tokenize(r" "), vec![" "]);233+ assert_eq!(tokenize(r"hello\, world!"), vec!["hello, world!"]);234+ assert_eq!(tokenize(r"\,"), vec![","]);235+ assert_eq!(tokenize(r"\,\,\,"), vec![",,,"]);236+ assert_eq!(tokenize(r"\n"), vec![r"\n"]);237+ assert_eq!(tokenize(r"\\"), vec![r"\"]);238+ assert_eq!(tokenize(r"\\\,"), vec![r"\,"]);239+}240+241+#[test]242+fn test_tokenize_multiple_values() {243+ assert_eq!(tokenize(r"foo,bar,baz"), vec!["foo", "bar", "baz"]);244+ assert_eq!(tokenize(r"hello world,foo"), vec!["hello world", "foo"]);245+246+ assert_eq!(tokenize(r"hello\,world!,baz"), vec!["hello,world!", "baz"]);247+}248+249+#[test]250+fn test_tokenize_empty_values() {251+ assert_eq!(tokenize(r"foo,,bar"), vec!["foo", "", "bar"]);252+ assert_eq!(tokenize(r",bar"), vec!["", "bar"]);253+ assert_eq!(tokenize(r"bar,"), vec!["bar", ""]);254+ assert_eq!(tokenize(r",,"), vec!["", "", ""]);255+}modified:src/main.rs+26 added-11 removed
5 unmodified lines6 use atty::Stream;7 use clap::ArgMatches;8 use colored::*;9 10-mod hyperfine;10+pub mod app;11+pub mod benchmark;12+pub mod benchmark_result;13+pub mod command;14+pub mod error;15+pub mod export;16+pub mod format;17+pub mod internal;18+pub mod options;19+pub mod outlier_detection;20+pub mod parameter_range;21+pub mod shell;22+pub mod timer;23+pub mod types;24+pub mod units;25+pub mod warnings;26 12-use crate::hyperfine::app::get_arg_matches;13-use crate::hyperfine::benchmark::{mean_shell_spawning_time, run_benchmark};14-use crate::hyperfine::command::Command;15-use crate::hyperfine::error::OptionsError;16-use crate::hyperfine::export::{ExportManager, ExportType};17-use crate::hyperfine::internal::{tokenize, write_benchmark_comparison};18-use crate::hyperfine::options::{CmdFailureAction, HyperfineOptions, OutputStyleOption};19-use crate::hyperfine::parameter_range::get_parameterized_commands;20-use crate::hyperfine::types::ParameterValue;21-use crate::hyperfine::units::Unit;27+use app::get_arg_matches;28+use benchmark::{mean_shell_spawning_time, run_benchmark};29+use command::Command;30+use error::OptionsError;31+use export::{ExportManager, ExportType};32+use internal::{tokenize, write_benchmark_comparison};33+use options::{CmdFailureAction, HyperfineOptions, OutputStyleOption};34+use parameter_range::get_parameterized_commands;35+use types::ParameterValue;36+use units::Unit;37 38 /// Print error message to stderr and terminate39 pub fn error(message: &str) -> ! {40 eprintln!("{} {}", "Error:".red(), message);382 unmodified linesadded:src/options.rs+107 added
1+use super::units::{Second, Unit};2+3+#[cfg(not(windows))]4+pub const DEFAULT_SHELL: &str = "sh";5+6+#[cfg(windows)]7+pub const DEFAULT_SHELL: &str = "cmd.exe";8+9+/// Action to take when an executed command fails.10+#[derive(Debug, Clone, Copy, PartialEq)]11+pub enum CmdFailureAction {12+ /// Exit with an error message13+ RaiseError,14+15+ /// Simply ignore the non-zero exit code16+ Ignore,17+}18+19+/// Output style type option20+#[derive(Debug, Clone, Copy, PartialEq)]21+pub enum OutputStyleOption {22+ /// Do not output with colors or any special formatting23+ Basic,24+25+ /// Output with full color and formatting26+ Full,27+28+ /// Keep elements such as progress bar, but use no coloring29+ NoColor,30+31+ /// Keep coloring, but use no progress bar32+ Color,33+34+ /// Disable all the output35+ Disabled,36+}37+38+/// Number of runs for a benchmark39+pub struct Runs {40+ /// Minimum number of benchmark runs41+ pub min: u64,42+43+ /// Maximum number of benchmark runs44+ pub max: Option<u64>,45+}46+47+impl Default for Runs {48+ fn default() -> Runs {49+ Runs { min: 10, max: None }50+ }51+}52+53+/// A set of options for hyperfine54+pub struct HyperfineOptions {55+ /// Number of warmup runs56+ pub warmup_count: u64,57+58+ /// Number of benchmark runs59+ pub runs: Runs,60+61+ /// Minimum benchmarking time62+ pub min_time_sec: Second,63+64+ /// Whether or not to ignore non-zero exit codes65+ pub failure_action: CmdFailureAction,66+67+ /// Command to run before each timing run68+ pub preparation_command: Option<Vec<String>>,69+70+ /// Command to run after each benchmark71+ pub cleanup_command: Option<String>,72+73+ /// What color mode to use for output74+ pub output_style: OutputStyleOption,75+76+ /// The shell to use for executing commands.77+ pub shell: String,78+79+ /// Forward benchmark's stdout to hyperfine's stdout80+ pub show_output: bool,81+82+ /// Which time unit to use for CLI & Markdown output83+ pub time_unit: Option<Unit>,84+85+ /// A list of custom command names that, if defined,86+ /// will be used instead of the command itself in87+ /// benchmark outputs.88+ pub names: Option<Vec<String>>,89+}90+91+impl Default for HyperfineOptions {92+ fn default() -> HyperfineOptions {93+ HyperfineOptions {94+ names: None,95+ warmup_count: 0,96+ runs: Runs::default(),97+ min_time_sec: 3.0,98+ failure_action: CmdFailureAction::RaiseError,99+ preparation_command: None,100+ cleanup_command: None,101+ output_style: OutputStyleOption::Full,102+ shell: DEFAULT_SHELL.to_string(),103+ show_output: false,104+ time_unit: None,105+ }106+ }107+}added:src/outlier_detection.rs+114 added
1+/// A module for statistical outlier detection.2+///3+/// References:4+/// - Boris Iglewicz and David Hoaglin (1993), "Volume 16: How to Detect and Handle Outliers",5+/// The ASQC Basic References in Quality Control: Statistical Techniques, Edward F. Mykytka,6+/// Ph.D., Editor.7+use statistical::median;8+9+/// Minimum modified Z-score for a datapoint to be an outlier. Here, 1.4826 is a factor that10+/// converts the MAD to an estimator for the standard deviation. The second factor is the number11+/// of standard deviations.12+pub const OUTLIER_THRESHOLD: f64 = 1.4826 * 10.0;13+14+/// Compute modifized Z-scores for a given sample. A (unmodified) Z-score is defined by15+/// `(x_i - x_mean)/x_stddev` whereas the modified Z-score is defined by `(x_i - x_median)/MAD`16+/// where MAD is the median absolute deviation.17+///18+/// References:19+/// - <https://en.wikipedia.org/wiki/Median_absolute_deviation>20+pub fn modified_zscores(xs: &[f64]) -> Vec<f64> {21+ assert!(!xs.is_empty());22+23+ // Compute sample median:24+ let x_median = median(xs);25+26+ // Compute the absolute deviations from the median:27+ let deviations: Vec<f64> = xs.iter().map(|x| (x - x_median).abs()).collect();28+29+ // Compute median absolute deviation:30+ let mad = median(&deviations);31+32+ // Handle MAD == 0 case33+ let mad = if mad > 0.0 { mad } else { f64::EPSILON };34+35+ // Compute modified Z-scores (x_i - x_median) / MAD36+ xs.iter().map(|&x| (x - x_median) / mad).collect()37+}38+39+/// Return the number of outliers in a given sample. Outliers are defined as data points with a40+/// modified Z-score that is larger than `OUTLIER_THRESHOLD`.41+#[cfg(test)]42+pub fn num_outliers(xs: &[f64]) -> usize {43+ if xs.is_empty() {44+ return 0;45+ }46+47+ let scores = modified_zscores(xs);48+ scores49+ .iter()50+ .filter(|&&s| s.abs() > OUTLIER_THRESHOLD)51+ .count()52+}53+54+#[test]55+fn test_detect_outliers() {56+ // Should not detect outliers in small samples57+ assert_eq!(0, num_outliers(&[]));58+ assert_eq!(0, num_outliers(&[50.0]));59+ assert_eq!(0, num_outliers(&[1000.0, 0.0]));60+61+ // Should not detect outliers in low-variance samples62+ let xs = [-0.2, 0.0, 0.2];63+ assert_eq!(0, num_outliers(&xs));64+65+ // Should detect a single outlier66+ let xs = [-0.2, 0.0, 0.2, 4.0];67+ assert_eq!(1, num_outliers(&xs));68+69+ // Should detect a single outlier70+ let xs = [0.5, 0.30, 0.29, 0.31, 0.30];71+ assert_eq!(1, num_outliers(&xs));72+73+ // Should detect no outliers in sample drawn from normal distribution74+ let xs = [75+ 2.33269488,76+ 1.42195907,77+ -0.57527698,78+ -0.31293437,79+ 2.2948158,80+ 0.75813273,81+ -1.0712388,82+ -0.96394741,83+ -1.15897446,84+ 1.10976285,85+ ];86+ assert_eq!(0, num_outliers(&xs));87+88+ // Should detect two outliers that were manually added89+ let xs = [90+ 2.33269488,91+ 1.42195907,92+ -0.57527698,93+ -0.31293437,94+ 2.2948158,95+ 0.75813273,96+ -1.0712388,97+ -0.96394741,98+ -1.15897446,99+ 1.10976285,100+ 20.0,101+ -500.0,102+ ];103+ assert_eq!(2, num_outliers(&xs));104+}105+106+#[test]107+fn test_detect_outliers_if_mad_becomes_0() {108+ // See https://stats.stackexchange.com/q/339932109+ let xs = [10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 100.0];110+ assert_eq!(1, num_outliers(&xs));111+112+ let xs = [10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 100.0, 100.0];113+ assert_eq!(2, num_outliers(&xs));114+}added:src/parameter_range.rs+317 added
1+use std::convert::TryInto;2+use std::ops::{Add, AddAssign, Div, Sub};3+use std::str::FromStr;4+5+use clap::Values;6+use rust_decimal::Decimal;7+8+use crate::command::Command;9+use crate::error::ParameterScanError;10+use crate::types::{NumericType, ParameterValue};11+12+trait Numeric:13+ Add<Output = Self>14+ + Sub<Output = Self>15+ + Div<Output = Self>16+ + AddAssign17+ + PartialOrd18+ + Copy19+ + Clone20+ + From<i32>21+ + Into<NumericType>22+{23+}24+impl<25+ T: Add<Output = Self>26+ + Sub<Output = Self>27+ + Div<Output = Self>28+ + AddAssign29+ + PartialOrd30+ + Copy31+ + Clone32+ + From<i32>33+ + Into<NumericType>,34+ > Numeric for T35+{36+}37+38+#[derive(Debug)]39+struct RangeStep<T> {40+ state: T,41+ end: T,42+ step: T,43+}44+45+impl<T: Numeric> RangeStep<T> {46+ fn new(start: T, end: T, step: T) -> Result<Self, ParameterScanError> {47+ if end < start {48+ return Err(ParameterScanError::EmptyRange);49+ }50+51+ if step == T::from(0) {52+ return Err(ParameterScanError::ZeroStep);53+ }54+55+ const MAX_PARAMETERS: usize = 100_000;56+ match range_step_size_hint(start, end, step) {57+ (_, Some(size)) if size <= MAX_PARAMETERS => Ok(Self {58+ state: start,59+ end,60+ step,61+ }),62+ _ => Err(ParameterScanError::TooLarge),63+ }64+ }65+}66+67+impl<T: Numeric> Iterator for RangeStep<T> {68+ type Item = T;69+70+ fn next(&mut self) -> Option<Self::Item> {71+ if self.state > self.end {72+ return None;73+ }74+ let return_val = self.state;75+ self.state += self.step;76+77+ Some(return_val)78+ }79+80+ fn size_hint(&self) -> (usize, Option<usize>) {81+ range_step_size_hint(self.state, self.end, self.step)82+ }83+}84+85+fn range_step_size_hint<T: Numeric>(start: T, end: T, step: T) -> (usize, Option<usize>) {86+ if step == T::from(0) {87+ return (usize::MAX, None);88+ }89+90+ let steps = (end - start + T::from(1)) / step;91+ steps92+ .into()93+ .try_into()94+ .map_or((usize::MAX, None), |u| (u, Some(u)))95+}96+97+fn build_parameterized_commands<'a, T: Numeric>(98+ param_min: T,99+ param_max: T,100+ step: T,101+ command_names: Vec<&'a str>,102+ command_strings: Vec<&'a str>,103+ param_name: &'a str,104+) -> Result<Vec<Command<'a>>, ParameterScanError> {105+ let param_range = RangeStep::new(param_min, param_max, step)?;106+ let param_count = param_range.size_hint().1.unwrap();107+ let command_name_count = command_names.len();108+109+ // `--command-name` should appear exactly once or exactly B times,110+ // where B is the total number of benchmarks.111+ if command_name_count > 1 && command_name_count != param_count {112+ return Err(ParameterScanError::UnexpectedCommandNameCount(113+ command_name_count,114+ param_count,115+ ));116+ }117+118+ let mut i = 0;119+ let mut commands = vec![];120+ for value in param_range {121+ for cmd in &command_strings {122+ let name = command_names123+ .get(i)124+ .or_else(|| command_names.get(0))125+ .copied();126+ commands.push(Command::new_parametrized(127+ name,128+ cmd,129+ vec![(param_name, ParameterValue::Numeric(value.into()))],130+ ));131+ i += 1;132+ }133+ }134+ Ok(commands)135+}136+137+pub fn get_parameterized_commands<'a>(138+ command_names: Option<Values<'a>>,139+ command_strings: Values<'a>,140+ mut vals: clap::Values<'a>,141+ step: Option<&str>,142+) -> Result<Vec<Command<'a>>, ParameterScanError> {143+ let command_names = command_names.map_or(vec![], |names| names.collect::<Vec<&str>>());144+ let command_strings = command_strings.collect::<Vec<&str>>();145+ let param_name = vals.next().unwrap();146+ let param_min = vals.next().unwrap();147+ let param_max = vals.next().unwrap();148+149+ // attempt to parse as integers150+ if let (Ok(param_min), Ok(param_max), Ok(step)) = (151+ param_min.parse::<i32>(),152+ param_max.parse::<i32>(),153+ step.unwrap_or("1").parse::<i32>(),154+ ) {155+ return build_parameterized_commands(156+ param_min,157+ param_max,158+ step,159+ command_names,160+ command_strings,161+ param_name,162+ );163+ }164+165+ // try parsing them as decimals166+ let param_min = Decimal::from_str(param_min)?;167+ let param_max = Decimal::from_str(param_max)?;168+169+ if step.is_none() {170+ return Err(ParameterScanError::StepRequired);171+ }172+173+ let step = Decimal::from_str(step.unwrap())?;174+ build_parameterized_commands(175+ param_min,176+ param_max,177+ step,178+ command_names,179+ command_strings,180+ param_name,181+ )182+}183+184+#[test]185+fn test_integer_range() {186+ let param_range: Vec<i32> = RangeStep::new(0, 10, 3).unwrap().collect();187+188+ assert_eq!(param_range.len(), 4);189+ assert_eq!(param_range[0], 0);190+ assert_eq!(param_range[3], 9);191+}192+193+#[test]194+fn test_decimal_range() {195+ let param_min = Decimal::from(0);196+ let param_max = Decimal::from(1);197+ let step = Decimal::from_str("0.1").unwrap();198+199+ let param_range: Vec<Decimal> = RangeStep::new(param_min, param_max, step)200+ .unwrap()201+ .collect();202+203+ assert_eq!(param_range.len(), 11);204+ assert_eq!(param_range[0], Decimal::from(0));205+ assert_eq!(param_range[10], Decimal::from(1));206+}207+208+#[test]209+fn test_range_step_validate() {210+ let result = RangeStep::new(0, 10, 3);211+ assert!(result.is_ok());212+213+ let result = RangeStep::new(214+ Decimal::from(0),215+ Decimal::from(1),216+ Decimal::from_str("0.1").unwrap(),217+ );218+ assert!(result.is_ok());219+220+ let result = RangeStep::new(11, 10, 1);221+ assert_eq!(format!("{}", result.unwrap_err()), "Empty parameter range");222+223+ let result = RangeStep::new(0, 10, 0);224+ assert_eq!(225+ format!("{}", result.unwrap_err()),226+ "Zero is not a valid parameter step"227+ );228+229+ let result = RangeStep::new(0, 100_001, 1);230+ assert_eq!(231+ format!("{}", result.unwrap_err()),232+ "Parameter range is too large"233+ );234+}235+236+#[test]237+fn test_get_parameterized_commands_int() {238+ let commands =239+ build_parameterized_commands(1i32, 7i32, 3i32, vec![], vec!["echo {val}"], "val").unwrap();240+ assert_eq!(commands.len(), 3);241+ assert_eq!(commands[2].get_name(), "echo 7");242+ assert_eq!(commands[2].get_shell_command(), "echo 7");243+}244+245+#[test]246+fn test_get_parameterized_commands_decimal() {247+ let param_min = Decimal::from_str("0").unwrap();248+ let param_max = Decimal::from_str("1").unwrap();249+ let step = Decimal::from_str("0.33").unwrap();250+251+ let commands = build_parameterized_commands(252+ param_min,253+ param_max,254+ step,255+ vec![],256+ vec!["echo {val}"],257+ "val",258+ )259+ .unwrap();260+ assert_eq!(commands.len(), 4);261+ assert_eq!(commands[3].get_name(), "echo 0.99");262+ assert_eq!(commands[3].get_shell_command(), "echo 0.99");263+}264+265+#[test]266+fn test_get_parameterized_command_names() {267+ let commands = build_parameterized_commands(268+ 1i32,269+ 3i32,270+ 1i32,271+ vec!["name-{val}"],272+ vec!["echo {val}"],273+ "val",274+ )275+ .unwrap();276+ assert_eq!(commands.len(), 3);277+ let command_names = commands278+ .iter()279+ .map(|c| c.get_name())280+ .collect::<Vec<String>>();281+ assert_eq!(command_names, vec!["name-1", "name-2", "name-3"]);282+}283+284+#[test]285+fn test_get_specified_command_names() {286+ let commands = build_parameterized_commands(287+ 1i32,288+ 3i32,289+ 1i32,290+ vec!["name-a", "name-b", "name-c"],291+ vec!["echo {val}"],292+ "val",293+ )294+ .unwrap();295+ assert_eq!(commands.len(), 3);296+ let command_names = commands297+ .iter()298+ .map(|c| c.get_name())299+ .collect::<Vec<String>>();300+ assert_eq!(command_names, vec!["name-a", "name-b", "name-c"]);301+}302+303+#[test]304+fn test_different_command_name_count_with_parameters() {305+ let result = build_parameterized_commands(306+ 1i32,307+ 3i32,308+ 1i32,309+ vec!["name-1", "name-2"],310+ vec!["echo {val}"],311+ "val",312+ );313+ assert_eq!(314+ format!("{}", result.unwrap_err()),315+ "'--command-name' has been specified 2 times. It has to appear exactly once, or exactly 3 times (number of benchmarks)"316+ );317+}added:src/shell.rs+96 added
1+use std::io;2+use std::process::{Command, ExitStatus, Stdio};3+4+use crate::timer::get_cpu_timer;5+6+/// Used to indicate the result of running a command7+#[derive(Debug, Copy, Clone)]8+pub struct ExecuteResult {9+ /// The amount of user time the process used10+ pub user_time: f64,11+12+ /// The amount of cpu time the process used13+ pub system_time: f64,14+15+ /// The exit status of the process16+ pub status: ExitStatus,17+}18+19+/// Execute the given command and return a timing summary20+#[cfg(windows)]21+pub fn execute_and_time(22+ stdout: Stdio,23+ stderr: Stdio,24+ command: &str,25+ shell: &str,26+) -> io::Result<ExecuteResult> {27+ let mut child = run_shell_command(stdout, stderr, command, shell)?;28+ let cpu_timer = get_cpu_timer(&child);29+ let status = child.wait()?;30+31+ let (user_time, system_time) = cpu_timer.stop();32+ Ok(ExecuteResult {33+ user_time,34+ system_time,35+ status,36+ })37+}38+39+/// Execute the given command and return a timing summary40+#[cfg(not(windows))]41+pub fn execute_and_time(42+ stdout: Stdio,43+ stderr: Stdio,44+ command: &str,45+ shell: &str,46+) -> io::Result<ExecuteResult> {47+ let cpu_timer = get_cpu_timer();48+49+ let status = run_shell_command(stdout, stderr, command, shell)?;50+51+ let (user_time, system_time) = cpu_timer.stop();52+53+ Ok(ExecuteResult {54+ user_time,55+ system_time,56+ status,57+ })58+}59+60+/// Run a standard shell command using `sh -c`61+#[cfg(not(windows))]62+fn run_shell_command(63+ stdout: Stdio,64+ stderr: Stdio,65+ command: &str,66+ shell: &str,67+) -> io::Result<std::process::ExitStatus> {68+ Command::new(shell)69+ .arg("-c")70+ .arg(command)71+ .env(72+ "HYPERFINE_RANDOMIZED_ENVIRONMENT_OFFSET",73+ "X".repeat(rand::random::<usize>() % 4096usize),74+ )75+ .stdin(Stdio::null())76+ .stdout(stdout)77+ .stderr(stderr)78+ .status()79+}80+81+/// Run a Windows shell command using `cmd.exe /C`82+#[cfg(windows)]83+fn run_shell_command(84+ stdout: Stdio,85+ stderr: Stdio,86+ command: &str,87+ shell: &str,88+) -> io::Result<std::process::Child> {89+ Command::new(shell)90+ .arg("/C")91+ .arg(command)92+ .stdin(Stdio::null())93+ .stdout(stdout)94+ .stderr(stderr)95+ .spawn()96+}added:src/types.rs+63 added
1+use serde::Serialize;2+use std::convert::TryFrom;3+use std::fmt;4+5+use rust_decimal::prelude::ToPrimitive;6+use rust_decimal::Decimal;7+8+#[derive(Debug, Clone, Serialize, Copy, PartialEq, Eq)]9+#[serde(untagged)]10+pub enum NumericType {11+ Int(i32),12+ Decimal(Decimal),13+}14+15+impl fmt::Display for NumericType {16+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {17+ match *self {18+ NumericType::Int(i) => fmt::Display::fmt(&i, f),19+ NumericType::Decimal(i) => fmt::Display::fmt(&i, f),20+ }21+ }22+}23+24+impl From<i32> for NumericType {25+ fn from(x: i32) -> NumericType {26+ NumericType::Int(x)27+ }28+}29+30+impl From<Decimal> for NumericType {31+ fn from(x: Decimal) -> NumericType {32+ NumericType::Decimal(x)33+ }34+}35+36+impl TryFrom<NumericType> for usize {37+ type Error = ();38+39+ fn try_from(numeric: NumericType) -> Result<Self, Self::Error> {40+ match numeric {41+ NumericType::Int(i) => usize::try_from(i).map_err(|_| ()),42+ NumericType::Decimal(d) => match d.to_u64() {43+ Some(u) => usize::try_from(u).map_err(|_| ()),44+ None => Err(()),45+ },46+ }47+ }48+}49+50+#[derive(Debug, Clone, PartialEq, Eq)]51+pub enum ParameterValue {52+ Text(String),53+ Numeric(NumericType),54+}55+56+impl<'a> ToString for ParameterValue {57+ fn to_string(&self) -> String {58+ match self {59+ ParameterValue::Text(ref value) => value.clone(),60+ ParameterValue::Numeric(value) => value.to_string(),61+ }62+ }63+}added:src/units.rs+45 added
1+/// This module contains common units.2+3+pub type Scalar = f64;4+5+/// Type alias for unit of time6+pub type Second = Scalar;7+8+/// Supported time units9+#[derive(Debug, Clone, Copy, PartialEq)]10+pub enum Unit {11+ Second,12+ MilliSecond,13+}14+15+impl Unit {16+ /// The abbreviation of the Unit.17+ pub fn short_name(self) -> String {18+ match self {19+ Unit::Second => String::from("s"),20+ Unit::MilliSecond => String::from("ms"),21+ }22+ }23+24+ /// Returns the Second value formatted for the Unit.25+ pub fn format(self, value: Second) -> String {26+ match self {27+ Unit::Second => format!("{:.3}", value),28+ Unit::MilliSecond => format!("{:.1}", value * 1e3),29+ }30+ }31+}32+33+#[test]34+fn test_unit_short_name() {35+ assert_eq!("s", Unit::Second.short_name());36+ assert_eq!("ms", Unit::MilliSecond.short_name());37+}38+39+// Note - the values are rounded when formatted.40+#[test]41+fn test_unit_format() {42+ let value: Second = 123.456789;43+ assert_eq!("123.457", Unit::Second.format(value));44+ assert_eq!("123456.8", Unit::MilliSecond.format(value));45+}added:src/warnings.rs+41 added
1+use std::fmt;2+3+use crate::format::format_duration;4+use crate::internal::MIN_EXECUTION_TIME;5+use crate::units::Second;6+7+/// A list of all possible warnings8+pub enum Warnings {9+ FastExecutionTime,10+ NonZeroExitCode,11+ SlowInitialRun(Second),12+ OutliersDetected,13+}14+15+impl fmt::Display for Warnings {16+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {17+ match *self {18+ Warnings::FastExecutionTime => write!(19+ f,20+ "Command took less than {:.0} ms to complete. Results might be inaccurate.",21+ MIN_EXECUTION_TIME * 1e322+ ),23+ Warnings::NonZeroExitCode => write!(f, "Ignoring non-zero exit code."),24+ Warnings::SlowInitialRun(t_first) => write!(25+ f,26+ "The first benchmarking run for this command was significantly slower than the \27+ rest ({}). This could be caused by (filesystem) caches that were not filled until \28+ after the first run. You should consider using the '--warmup' option to fill \29+ those caches before the actual benchmark. Alternatively, use the '--prepare' \30+ option to clear the caches before each timing run.",31+ format_duration(t_first, None)32+ ),33+ Warnings::OutliersDetected => write!(34+ f,35+ "Statistical outliers were detected. Consider re-running this benchmark on a quiet \36+ PC without any interferences from other programs. It might help to use the \37+ '--warmup' or '--prepare' options."38+ ),39+ }40+ }41+}modified:build.rs+1 added-1 removed
1 use std::fs;2 3 use clap::Shell;4 5-include!("src/hyperfine/app.rs");5+include!("src/app.rs");6 7 fn main() {8 let min_version = "1.39";9 22 unmodified lines