Skip to content
Myr

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

51 files+3148 added−3149 removed

added:src/export/asciidoc.rs+237 added
1use super::Exporter;23use crate::benchmark_result::BenchmarkResult;4use crate::format::format_duration_value;5use crate::units::Unit;67use std::io::Result;89#[derive(Default)]10pub struct AsciidocExporter {}1112impl 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 };2425 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());3435 Ok(res)36 }37}3839fn table_open() -> Vec<u8> {40 "[cols=\"<,>,>\"]\n".bytes().collect()41}4243fn table_startend() -> Vec<u8> {44 "|===\n".bytes().collect()45}4647fn 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}5556fn 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}7071/// Ensure various options for the header generate correct results72#[test]73fn 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);7879 assert_eq!(conms, genms);80 assert_eq!(cons, gens);81}8283/// Ensure each table row is generated properly84#[test]85fn 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 );105106 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();128129 let genms = table_row(&result, Unit::MilliSecond);130 let gens = table_row(&result, Unit::Second);131132 assert_eq!(expms, genms);133 assert_eq!(exps, gens);134}135136/// Ensure commands get properly escaped137#[test]138fn 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);169170 assert_eq!(exps, gens);171}172173/// Integration test174#[test]175fn 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();235236 assert_eq!(exps, gens);237}
added:src/export/csv.rs+107 added
1use super::Exporter;23use crate::benchmark_result::BenchmarkResult;4use crate::units::Unit;56use std::borrow::Cow;7use std::io::{Error, ErrorKind, Result};89use csv::WriterBuilder;1011#[derive(Default)]12pub struct CsvExporter {}1314impl Exporter for CsvExporter {15 fn serialize(&self, results: &[BenchmarkResult], _unit: Option<Unit>) -> Result<Vec<u8>> {16 let mut writer = WriterBuilder::new().from_writer(vec![]);1718 {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 }3334 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 }4647 writer48 .into_inner()49 .map_err(|e| Error::new(ErrorKind::Other, e))50 }51}5253#[test]54fn test_csv() {55 use std::collections::BTreeMap;56 let exporter = CsvExporter::default();5758 // 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();105106 assert_eq!(exps, gens);107}
added:src/export/json.rs+27 added
1use super::Exporter;2use crate::benchmark_result::BenchmarkResult;3use crate::units::Unit;45use std::io::{Error, ErrorKind, Result};67use serde::*;8use serde_json::to_vec_pretty;910#[derive(Serialize, Debug)]11struct HyperfineSummary<'a> {12 results: &'a [BenchmarkResult],13}1415#[derive(Default)]16pub struct JsonExporter {}1718impl 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 }2425 output.map_err(|e| Error::new(ErrorKind::Other, e))26 }27}
added:src/export/markdown.rs+293 added
1use super::Exporter;23use crate::benchmark_result::BenchmarkResult;4use crate::format::format_duration_value;5use crate::internal::{compute_relative_speed, BenchmarkResultWithRelativeSpeed};6use crate::units::Unit;78use std::io::{Error, ErrorKind, Result};910#[derive(Default)]11pub struct MarkdownExporter {}1213impl 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 };2526 if let Some(annotated_results) = compute_relative_speed(results) {27 let mut destination = start_table(unit);2829 for result in annotated_results {30 add_table_row(&mut destination, &result, unit);31 }3233 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}4243fn 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}4950fn start_table(unit: Unit) -> Vec<u8> {51 table_header(unit.short_name()).bytes().collect()52}5354fn 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 };6667 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}8182/// 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]89fn test_markdown_format_ms() {90 use std::collections::BTreeMap;91 let exporter = MarkdownExporter::default();9293 let mut timing_results = vec![];9495 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 ));108109 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 ));122123 let formatted = String::from_utf8(exporter.serialize(&timing_results, None).unwrap()).unwrap();124125 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 );132133 assert_eq!(formatted_expected, formatted);134}135136/// 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]139fn test_markdown_format_s() {140 use std::collections::BTreeMap;141 let exporter = MarkdownExporter::default();142143 let mut timing_results = vec![];144145 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 ));158159 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 ));172173 let formatted = String::from_utf8(exporter.serialize(&timing_results, None).unwrap()).unwrap();174175 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 );182183 assert_eq!(formatted_expected, formatted);184}185186/// The given time unit (s) is used to set the units for all entries.187#[test]188fn test_markdown_format_time_unit_s() {189 use std::collections::BTreeMap;190 let exporter = MarkdownExporter::default();191192 let mut timing_results = vec![];193194 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 ));207208 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 ));221222 let formatted = String::from_utf8(223 exporter224 .serialize(&timing_results, Some(Unit::Second))225 .unwrap(),226 )227 .unwrap();228229 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 );236237 assert_eq!(formatted_expected, formatted);238}239240/// This (again) demonstrates that the given time unit (ms) is used to set241/// the units for all entries.242#[test]243fn test_markdown_format_time_unit_ms() {244 use std::collections::BTreeMap;245 let exporter = MarkdownExporter::default();246247 let mut timing_results = vec![];248249 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 ));262263 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 ));276277 let formatted = String::from_utf8(278 exporter279 .serialize(&timing_results, Some(Unit::MilliSecond))280 .unwrap(),281 )282 .unwrap();283284 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 );291292 assert_eq!(formatted_expected, formatted);293}
added:src/export/mod.rs+89 added
1mod asciidoc;2mod csv;3mod json;4mod markdown;56use self::asciidoc::AsciidocExporter;7use self::csv::CsvExporter;8use self::json::JsonExporter;9use self::markdown::MarkdownExporter;1011use std::fs::{File, OpenOptions};12use std::io::{Result, Write};1314use crate::benchmark_result::BenchmarkResult;15use crate::units::Unit;1617/// The desired form of exporter to use for a given file.18#[derive(Clone)]19pub enum ExportType {20 /// Asciidoc Table21 Asciidoc,2223 /// CSV (comma separated values) format24 Csv,2526 /// JSON format27 Json,2829 /// Markdown table30 Markdown,31}3233/// Interface for different exporters.34trait Exporter {35 /// Export the given entries in the serialized form.36 fn serialize(&self, results: &[BenchmarkResult], unit: Option<Unit>) -> Result<Vec<u8>>;37}3839struct ExporterWithFilename {40 exporter: Box<dyn Exporter>,41 filename: String,42}4344/// Handles the management of multiple file exporters.45pub struct ExportManager {46 exporters: Vec<ExporterWithFilename>,47}4849impl ExportManager {50 /// Create a new ExportManager51 pub fn new() -> ExportManager {52 ExportManager {53 exporters: Vec::new(),54 }55 }5657 /// Add an additional exporter to the ExportManager58 pub fn add_exporter(&mut self, export_type: ExportType, filename: &str) -> Result<()> {59 let _ = File::create(filename)?;6061 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 });7172 Ok(())73 }7475 /// 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}8485/// Write the given content to a file with the specified name86fn 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
1use super::Exporter;23use crate::hyperfine::benchmark_result::BenchmarkResult;4use crate::hyperfine::format::format_duration_value;5use crate::hyperfine::units::Unit;67use std::io::Result;89#[derive(Default)]10pub struct AsciidocExporter {}1112impl 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 };2425 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());3435 Ok(res)36 }37}3839fn table_open() -> Vec<u8> {40 "[cols=\"<,>,>\"]\n".bytes().collect()41}4243fn table_startend() -> Vec<u8> {44 "|===\n".bytes().collect()45}4647fn 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}5556fn 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}7071/// Ensure various options for the header generate correct results72#[test]73fn 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);7879 assert_eq!(conms, genms);80 assert_eq!(cons, gens);81}8283/// Ensure each table row is generated properly84#[test]85fn 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 );105106 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();128129 let genms = table_row(&result, Unit::MilliSecond);130 let gens = table_row(&result, Unit::Second);131132 assert_eq!(expms, genms);133 assert_eq!(exps, gens);134}135136/// Ensure commands get properly escaped137#[test]138fn 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);169170 assert_eq!(exps, gens);171}172173/// Integration test174#[test]175fn 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();235236 assert_eq!(exps, gens);237}
deleted:src/hyperfine/export/csv.rs-107 removed
1use super::Exporter;23use crate::hyperfine::benchmark_result::BenchmarkResult;4use crate::hyperfine::units::Unit;56use std::borrow::Cow;7use std::io::{Error, ErrorKind, Result};89use csv::WriterBuilder;1011#[derive(Default)]12pub struct CsvExporter {}1314impl Exporter for CsvExporter {15 fn serialize(&self, results: &[BenchmarkResult], _unit: Option<Unit>) -> Result<Vec<u8>> {16 let mut writer = WriterBuilder::new().from_writer(vec![]);1718 {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 }3334 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 }4647 writer48 .into_inner()49 .map_err(|e| Error::new(ErrorKind::Other, e))50 }51}5253#[test]54fn test_csv() {55 use std::collections::BTreeMap;56 let exporter = CsvExporter::default();5758 // 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();105106 assert_eq!(exps, gens);107}
deleted:src/hyperfine/export/json.rs-27 removed
1use super::Exporter;2use crate::hyperfine::benchmark_result::BenchmarkResult;3use crate::hyperfine::units::Unit;45use std::io::{Error, ErrorKind, Result};67use serde::*;8use serde_json::to_vec_pretty;910#[derive(Serialize, Debug)]11struct HyperfineSummary<'a> {12 results: &'a [BenchmarkResult],13}1415#[derive(Default)]16pub struct JsonExporter {}1718impl 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 }2425 output.map_err(|e| Error::new(ErrorKind::Other, e))26 }27}
deleted:src/hyperfine/export/markdown.rs-293 removed
1use super::Exporter;23use crate::hyperfine::benchmark_result::BenchmarkResult;4use crate::hyperfine::format::format_duration_value;5use crate::hyperfine::internal::{compute_relative_speed, BenchmarkResultWithRelativeSpeed};6use crate::hyperfine::units::Unit;78use std::io::{Error, ErrorKind, Result};910#[derive(Default)]11pub struct MarkdownExporter {}1213impl 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 };2526 if let Some(annotated_results) = compute_relative_speed(results) {27 let mut destination = start_table(unit);2829 for result in annotated_results {30 add_table_row(&mut destination, &result, unit);31 }3233 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}4243fn 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}4950fn start_table(unit: Unit) -> Vec<u8> {51 table_header(unit.short_name()).bytes().collect()52}5354fn 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 };6667 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}8182/// 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]89fn test_markdown_format_ms() {90 use std::collections::BTreeMap;91 let exporter = MarkdownExporter::default();9293 let mut timing_results = vec![];9495 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 ));108109 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 ));122123 let formatted = String::from_utf8(exporter.serialize(&timing_results, None).unwrap()).unwrap();124125 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 );132133 assert_eq!(formatted_expected, formatted);134}135136/// 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]139fn test_markdown_format_s() {140 use std::collections::BTreeMap;141 let exporter = MarkdownExporter::default();142143 let mut timing_results = vec![];144145 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 ));158159 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 ));172173 let formatted = String::from_utf8(exporter.serialize(&timing_results, None).unwrap()).unwrap();174175 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 );182183 assert_eq!(formatted_expected, formatted);184}185186/// The given time unit (s) is used to set the units for all entries.187#[test]188fn test_markdown_format_time_unit_s() {189 use std::collections::BTreeMap;190 let exporter = MarkdownExporter::default();191192 let mut timing_results = vec![];193194 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 ));207208 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 ));221222 let formatted = String::from_utf8(223 exporter224 .serialize(&timing_results, Some(Unit::Second))225 .unwrap(),226 )227 .unwrap();228229 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 );236237 assert_eq!(formatted_expected, formatted);238}239240/// This (again) demonstrates that the given time unit (ms) is used to set241/// the units for all entries.242#[test]243fn test_markdown_format_time_unit_ms() {244 use std::collections::BTreeMap;245 let exporter = MarkdownExporter::default();246247 let mut timing_results = vec![];248249 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 ));262263 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 ));276277 let formatted = String::from_utf8(278 exporter279 .serialize(&timing_results, Some(Unit::MilliSecond))280 .unwrap(),281 )282 .unwrap();283284 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 );291292 assert_eq!(formatted_expected, formatted);293}
deleted:src/hyperfine/export/mod.rs-89 removed
1mod asciidoc;2mod csv;3mod json;4mod markdown;56use self::asciidoc::AsciidocExporter;7use self::csv::CsvExporter;8use self::json::JsonExporter;9use self::markdown::MarkdownExporter;1011use std::fs::{File, OpenOptions};12use std::io::{Result, Write};1314use crate::hyperfine::benchmark_result::BenchmarkResult;15use crate::hyperfine::units::Unit;1617/// The desired form of exporter to use for a given file.18#[derive(Clone)]19pub enum ExportType {20 /// Asciidoc Table21 Asciidoc,2223 /// CSV (comma separated values) format24 Csv,2526 /// JSON format27 Json,2829 /// Markdown table30 Markdown,31}3233/// Interface for different exporters.34trait Exporter {35 /// Export the given entries in the serialized form.36 fn serialize(&self, results: &[BenchmarkResult], unit: Option<Unit>) -> Result<Vec<u8>>;37}3839struct ExporterWithFilename {40 exporter: Box<dyn Exporter>,41 filename: String,42}4344/// Handles the management of multiple file exporters.45pub struct ExportManager {46 exporters: Vec<ExporterWithFilename>,47}4849impl ExportManager {50 /// Create a new ExportManager51 pub fn new() -> ExportManager {52 ExportManager {53 exporters: Vec::new(),54 }55 }5657 /// Add an additional exporter to the ExportManager58 pub fn add_exporter(&mut self, export_type: ExportType, filename: &str) -> Result<()> {59 let _ = File::create(filename)?;6061 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 });7172 Ok(())73 }7475 /// 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}8485/// Write the given content to a file with the specified name86fn 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
1use crate::hyperfine::units::Second;23#[derive(Debug, Copy, Clone)]4pub struct CPUTimes {5 /// Total amount of time spent executing in user mode6 pub user_usec: i64,78 /// Total amount of time spent executing in kernel mode9 pub system_usec: i64,10}1112#[derive(Debug, Copy, Clone)]13pub struct CPUInterval {14 /// Total amount of time spent executing in user mode15 pub user: Second,1617 /// Total amount of time spent executing in kernel mode18 pub system: Second,19}
deleted:src/hyperfine/timer/mod.rs-28 removed
1mod internal;23pub mod wallclocktimer;45use cfg_if::cfg_if;67cfg_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}16use std::process::Child;1718/// Defines start functionality of a timer.19pub trait TimerStart {20 fn start() -> Self;21 fn start_for_process(process: &Child) -> Self;22}2324/// Defines stop functionality of a timer.25pub 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))]23use super::internal::{CPUInterval, CPUTimes};4use crate::hyperfine::timer::{TimerStart, TimerStop};5use crate::hyperfine::units::Second;67use std::mem;8use std::process::Child;910pub fn get_cpu_timer() -> Box<dyn TimerStop<Result = (Second, Second)>> {11 Box::new(CPUTimer::start())12}1314struct CPUTimer {15 start_cpu: CPUTimes,16}1718impl TimerStart for CPUTimer {19 fn start() -> Self {20 CPUTimer {21 start_cpu: get_cpu_times(),22 }23 }2425 fn start_for_process(_: &Child) -> Self {26 Self::start()27 }28}2930impl TimerStop for CPUTimer {31 type Result = (Second, Second);3233 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}3940/// Read CPU execution times ('user' and 'system')41fn get_cpu_times() -> CPUTimes {42 use libc::{getrusage, rusage, RUSAGE_CHILDREN};4344 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 };5051 const MICROSEC_PER_SEC: i64 = 1000 * 1000;5253 #[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}6162/// Compute the time intervals in between two `CPUTimes` snapshots63fn 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}6970#[cfg(test)]71use approx::assert_relative_eq;7273#[test]74fn test_cpu_time_interval() {75 let t_a = CPUTimes {76 user_usec: 12345,77 system_usec: 54321,78 };7980 let t_b = CPUTimes {81 user_usec: 20000,82 system_usec: 70000,83 };8485 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);8889 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);9293 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
1use std::process::Child;2use std::time::Instant;34use crate::hyperfine::timer::{TimerStart, TimerStop};5use crate::hyperfine::units::Second;67pub struct WallClockTimer {8 start: Instant,9}1011impl TimerStart for WallClockTimer {12 fn start() -> WallClockTimer {13 WallClockTimer {14 start: Instant::now(),15 }16 }1718 fn start_for_process(_: &Child) -> Self {19 Self::start()20 }21}2223impl TimerStop for WallClockTimer {24 type Result = Second;2526 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)]23use super::internal::CPUTimes;4use crate::hyperfine::timer::{TimerStart, TimerStop};5use crate::hyperfine::units::Second;67use winapi::um::processthreadsapi::GetProcessTimes;8use winapi::um::winnt::HANDLE;910use std::mem;11use std::os::windows::io::{AsRawHandle, RawHandle};12use std::process::Child;1314const HUNDRED_NS_PER_MS: i64 = 10;1516pub fn get_cpu_timer(process: &Child) -> Box<dyn TimerStop<Result = (Second, Second)>> {17 Box::new(CPUTimer::start_for_process(process))18}1920struct CPUTimer {21 handle: RawHandle,22}2324impl TimerStart for CPUTimer {25 fn start() -> Self {26 panic!()27 }2829 fn start_for_process(process: &Child) -> Self {30 CPUTimer {31 handle: process.as_raw_handle(),32 }33 }34}3536impl TimerStop for CPUTimer {37 type Result = (Second, Second);3839 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}4748/// Read CPU execution times (dummy for now)49fn 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 );6263 // 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 };7879 CPUTimes {80 user_usec,81 system_usec,82 }83}
deleted:src/hyperfine/app.rs-242 removed
1use atty::Stream;2use clap::{crate_version, App, AppSettings, Arg, ArgMatches};3use std::ffi::OsString;45pub fn get_arg_matches<I, T>(args: I) -> ArgMatches<'static>6where7 I: IntoIterator<Item = T>,8 T: Into<OsString> + Clone,9{10 let app = build_app();11 app.get_matches_from(args)12}1314/// Build the clap app for parsing command line arguments15fn build_app() -> App<'static, 'static> {16 let clap_color_setting = if atty::is(Stream::Stdout) {17 AppSettings::ColoredHelp18 } else {19 AppSettings::ColorNever20 };2122 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
1use serde::Serialize;2use std::collections::BTreeMap;34use crate::hyperfine::units::Second;56/// 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)]10pub struct BenchmarkResult {11 /// The command that was run12 pub command: String,1314 /// The mean run time15 pub mean: Second,1617 /// The standard deviation of all run times18 pub stddev: Second,1920 /// The median run time21 pub median: Second,2223 /// Time spend in user space24 pub user: Second,2526 /// Time spent in system space27 pub system: Second,2829 /// Min time measured30 pub min: Second,3132 /// Max time measured33 pub max: Second,3435 /// All run time measurements36 #[serde(skip_serializing_if = "Option::is_none")]37 pub times: Option<Vec<Second>>,3839 /// All run exit codes40 pub exit_codes: Vec<Option<i32>>,4142 /// Any parameter values used43 #[serde(skip_serializing_if = "BTreeMap::is_empty")]44 pub parameters: BTreeMap<String, String>,45}4647impl 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
1use std::cmp;2use std::io;3use std::process::{ExitStatus, Stdio};45use colored::*;6use statistical::{mean, median, standard_deviation};78use crate::hyperfine::benchmark_result::BenchmarkResult;9use crate::hyperfine::command::Command;10use crate::hyperfine::format::{format_duration, format_duration_unit};11use crate::hyperfine::internal::{get_progress_bar, max, min, MIN_EXECUTION_TIME};12use crate::hyperfine::options::{CmdFailureAction, HyperfineOptions, OutputStyleOption};13use crate::hyperfine::outlier_detection::{modified_zscores, OUTLIER_THRESHOLD};14use crate::hyperfine::shell::execute_and_time;15use crate::hyperfine::timer::wallclocktimer::WallClockTimer;16use crate::hyperfine::timer::{TimerStart, TimerStop};17use crate::hyperfine::units::Second;18use crate::hyperfine::warnings::Warnings;1920/// Results from timing a single shell command21#[derive(Debug, Default, Copy, Clone)]22pub struct TimingResult {23 /// Wall clock time24 pub time_real: Second,2526 /// Time spent in user mode27 pub time_user: Second,2829 /// Time spent in kernel mode30 pub time_system: Second,31}3233/// Correct for shell spawning time34fn 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}4142/// Run the given shell command and measure the execution time43pub 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 };5556 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();5960 let mut time_user = result.user_time;61 let mut time_system = result.system_time;6263 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 }7778 // 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 }8485 Ok((86 TimingResult {87 time_real,88 time_user,89 time_system,90 },91 result.status,92 ))93}9495/// Measure the average shell spawning time96pub 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 };111112 let mut times_real: Vec<Second> = vec![];113 let mut times_user: Vec<Second> = vec![];114 let mut times_system: Vec<Second> = vec![];115116 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 );125126 match res {127 Err(_) => {128 let shell_cmd = if cfg!(windows) {129 format!("{} /C \"\"", shell)130 } else {131 format!("{} -c \"\"", shell)132 };133134 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 }149150 if let Some(bar) = progress_bar.as_ref() {151 bar.inc(1)152 }153 }154155 if let Some(bar) = progress_bar.as_ref() {156 bar.finish_and_clear()157 }158159 Ok(TimingResult {160 time_real: mean(&times_real),161 time_user: mean(&times_user),162 time_system: mean(&times_system),163 })164}165166fn 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}183184/// Run the command specified by `--prepare`.185fn 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.";192193 run_intermediate_command(shell, command, show_output, error_output)194}195196/// Run the command specified by `--cleanup`.197fn 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.";204205 run_intermediate_command(shell, command, show_output, error_output)206}207208#[cfg(unix)]209fn extract_exit_code(status: ExitStatus) -> Option<i32> {210 use std::os::unix::process::ExitStatusExt;211212 /* 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}223224#[cfg(not(unix))]225fn extract_exit_code(status: ExitStatus) -> Option<i32> {226 status.code()227}228229/// Run the benchmark for a single shell command230pub 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 }245246 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;251252 // 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 });261262 // 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 };273274 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 }291292 // 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 };302303 let prepare_res = run_preparation_command(&options.shell, &prepare_cmd, options.show_output)?;304305 // 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();314315 // 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;319320 let count = {321 let min = cmp::max(runs_in_min_time, options.runs.min);322323 options324 .runs325 .max326 .as_ref()327 .map(|max| cmp::min(min, *max))328 .unwrap_or(min)329 };330331 let count_remaining = count - 1;332333 // 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));338339 all_succeeded = all_succeeded && success;340341 // 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 }348349 // Gather statistics350 for _ in 0..count_remaining {351 run_preparation_command(&options.shell, &prepare_cmd, options.show_output)?;352353 let msg = {354 let mean = format_duration(mean(&times_real), options.time_unit);355 format!("Current estimate: {}", mean.to_string().green())356 };357358 if let Some(bar) = progress_bar.as_ref() {359 bar.set_message(msg.to_owned())360 }361362 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();370371 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));375376 all_succeeded = all_succeeded && success;377378 if let Some(bar) = progress_bar.as_ref() {379 bar.inc(1)380 }381 }382383 if let Some(bar) = progress_bar.as_ref() {384 bar.finish_and_clear()385 }386387 // Compute statistical quantities388 let t_num = times_real.len();389 let t_mean = mean(&times_real);390 let t_stddev = standard_deviation(&times_real, Some(t_mean));391 let t_median = median(&times_real);392 let t_min = min(&times_real);393 let t_max = max(&times_real);394395 let user_mean = mean(&times_user);396 let system_mean = mean(&times_system);397398 // 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);404405 let user_str = format_duration(user_mean, Some(time_unit));406 let system_str = format_duration(system_mean, Some(time_unit));407408 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 );418419 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 }428429 // Warnings430 let mut warnings = vec![];431432 // Check execution time433 if times_real.iter().any(|&t| t < MIN_EXECUTION_TIME) {434 warnings.push(Warnings::FastExecutionTime);435 }436437 // Check programm exit codes438 if !all_succeeded {439 warnings.push(Warnings::NonZeroExitCode);440 }441442 // Run outlier detection443 let scores = modified_zscores(&times_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 }449450 if !warnings.is_empty() {451 eprintln!(" ");452453 for warning in &warnings {454 eprintln!(" {}: {}", "Warning".yellow(), warning);455 }456 }457458 if options.output_style != OutputStyleOption::Disabled {459 println!(" ");460 }461462 // 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)?;467468 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
1use std::collections::BTreeMap;2use std::fmt;34use super::types::ParameterValue;56/// A command that should be benchmarked.7#[derive(Debug, Clone, PartialEq, Eq)]8pub struct Command<'a> {9 /// The command name (without parameter substitution)10 name: Option<&'a str>,1112 /// The command that should be executed (without parameter substitution)13 expression: &'a str,1415 /// Zero or more parameter values.16 parameters: Vec<(&'a str, ParameterValue)>,17}1819impl<'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 }2728 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 }3940 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 }4647 pub fn get_shell_command(&self) -> String {48 self.replace_parameters_in(self.expression)49 }5051 pub fn get_parameters(&self) -> &Vec<(&'a str, ParameterValue)> {52 &self.parameters53 }5455 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}8485#[test]86fn 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}9798#[test]99fn 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}110111impl<'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
1use rust_decimal::Error as DecimalError;2use std::error::Error;3use std::fmt;4use std::num;5use std::num::ParseIntError;67#[derive(Debug)]8pub enum ParameterScanError {9 ParseIntError(num::ParseIntError),10 ParseDecimalError(DecimalError),11 EmptyRange,12 TooLarge,13 ZeroStep,14 StepRequired,15 UnexpectedCommandNameCount(usize, usize),16}1718impl From<num::ParseIntError> for ParameterScanError {19 fn from(e: num::ParseIntError) -> ParameterScanError {20 ParameterScanError::ParseIntError(e)21 }22}2324impl From<DecimalError> for ParameterScanError {25 fn from(e: DecimalError) -> ParameterScanError {26 ParameterScanError::ParseDecimalError(e)27 }28}2930impl 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}5455impl Error for ParameterScanError {}5657#[derive(Debug)]58pub enum OptionsError<'a> {59 RunsBelowTwo,60 EmptyRunsRange,61 TooManyCommandNames(usize),62 UnexpectedCommandNameCount(usize, usize),63 NumericParsingError(&'a str, ParseIntError),64}6566impl<'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}9091impl<'a> Error for OptionsError<'a> {}
deleted:src/hyperfine/format.rs-65 removed
1use crate::hyperfine::units::{Second, Unit};23/// 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.5pub fn format_duration(duration: Second, unit: Option<Unit>) -> String {6 let (duration_fmt, _) = format_duration_unit(duration, unit);7 duration_fmt8}910/// Like `format_duration`, but returns the target unit as well.11pub fn format_duration_unit(duration: Second, unit: Option<Unit>) -> (String, Unit) {12 let (out_str, out_unit) = format_duration_value(duration, unit);1314 (format!("{} {}", out_str, out_unit.short_name()), out_unit)15}1617/// Like `format_duration`, but returns the target unit as well.18pub 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}2526#[test]27fn test_format_duration_unit_basic() {28 let (out_str, out_unit) = format_duration_unit(1.3, None);2930 assert_eq!("1.300 s", out_str);31 assert_eq!(Unit::Second, out_unit);3233 let (out_str, out_unit) = format_duration_unit(1.0, None);3435 assert_eq!("1.000 s", out_str);36 assert_eq!(Unit::Second, out_unit);3738 let (out_str, out_unit) = format_duration_unit(0.999, None);3940 assert_eq!("999.0 ms", out_str);41 assert_eq!(Unit::MilliSecond, out_unit);4243 let (out_str, out_unit) = format_duration_unit(0.0, None);4445 assert_eq!("0.0 ms", out_str);46 assert_eq!(Unit::MilliSecond, out_unit);4748 let (out_str, out_unit) = format_duration_unit(1000.0, None);4950 assert_eq!("1000.000 s", out_str);51 assert_eq!(Unit::Second, out_unit);52}5354#[test]55fn test_format_duration_unit_with_unit() {56 let (out_str, out_unit) = format_duration_unit(1.3, Some(Unit::Second));5758 assert_eq!("1.300 s", out_str);59 assert_eq!(Unit::Second, out_unit);6061 let (out_str, out_unit) = format_duration_unit(1.3, Some(Unit::MilliSecond));6263 assert_eq!("1300.0 ms", out_str);64 assert_eq!(Unit::MilliSecond, out_unit);65}
deleted:src/hyperfine/internal.rs-255 removed
1use colored::*;2use indicatif::{ProgressBar, ProgressStyle};34use crate::hyperfine::benchmark_result::BenchmarkResult;5use crate::hyperfine::options::OutputStyleOption;6use crate::hyperfine::units::{Scalar, Second};78use std::cmp::Ordering;9use std::iter::Iterator;1011/// Threshold for warning about fast execution time12pub const MIN_EXECUTION_TIME: Second = 5e-3;1314#[cfg(not(windows))]15const TICK_SETTINGS: (&str, u64) = ("⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏ ", 80);1617#[cfg(windows)]18const TICK_SETTINGS: (&str, u64) = (r"+-x| ", 200);1920/// Return a pre-configured progress bar21pub 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 };2829 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());3637 progress_bar38}3940/// A max function for f64's without NaNs41pub fn max(vals: &[f64]) -> f64 {42 *vals43 .iter()44 .max_by(|a, b| a.partial_cmp(b).unwrap())45 .unwrap()46}4748/// A min function for f64's without NaNs49pub fn min(vals: &[f64]) -> f64 {50 *vals51 .iter()52 .min_by(|a, b| a.partial_cmp(b).unwrap())53 .unwrap()54}5556#[derive(Debug)]57pub 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}6364fn compare_mean_time(l: &BenchmarkResult, r: &BenchmarkResult) -> Ordering {65 l.mean.partial_cmp(&r.mean).unwrap_or(Ordering::Equal)66}6768pub 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");7576 if fastest.mean == 0.0 {77 return None;78 }7980 Some(81 results82 .iter()83 .map(|result| {84 let ratio = result.mean / fastest.mean;8586 // 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();9293 BenchmarkResultWithRelativeSpeed {94 result,95 relative_speed: ratio,96 relative_speed_stddev: ratio_stddev,97 is_fastest: result == fastest,98 }99 })100 .collect(),101 )102}103104pub fn write_benchmark_comparison(results: &[BenchmarkResult]) {105 if results.len() < 2 {106 return;107 }108109 if let Some(mut annotated_results) = compute_relative_speed(results) {110 annotated_results.sort_by(|l, r| compare_mean_time(l.result, r.result));111112 let fastest = &annotated_results[0];113 let others = &annotated_results[1..];114115 println!("{}", "Summary".bold());116 println!(" '{}' ran", fastest.result.command.cyan());117118 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}137138#[test]139fn test_max() {140 let assert_float_eq = |a, b| {141 assert!((a - b) < f64::EPSILON);142 };143144 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}150151#[cfg(test)]152fn create_result(name: &str, mean: Scalar) -> BenchmarkResult {153 use std::collections::BTreeMap;154155 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}169170#[test]171fn test_compute_relative_speed() {172 use approx::assert_relative_eq;173174 let results = vec![175 create_result("cmd1", 3.0),176 create_result("cmd2", 2.0),177 create_result("cmd3", 5.0),178 ];179180 let annotated_results = compute_relative_speed(&results).unwrap();181182 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}186187#[test]188fn test_compute_relative_speed_for_zero_times() {189 let results = vec![create_result("cmd1", 1.0), create_result("cmd2", 0.0)];190191 let annotated_results = compute_relative_speed(&results);192193 assert!(annotated_results.is_none());194}195196pub fn tokenize(values: &str) -> Vec<String> {197 let mut tokens = vec![];198 let mut buf = String::new();199200 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 }222223 tokens.push(buf);224225 tokens226}227228#[test]229fn 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}240241#[test]242fn 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"]);245246 assert_eq!(tokenize(r"hello\,world!,baz"), vec!["hello,world!", "baz"]);247}248249#[test]250fn 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
1pub mod app;2pub mod benchmark;3pub mod benchmark_result;4pub mod command;5pub mod error;6pub mod export;7pub mod format;8pub mod internal;9pub mod options;10pub mod outlier_detection;11pub mod parameter_range;12pub mod shell;13pub mod timer;14pub mod types;15pub mod units;16pub mod warnings;
deleted:src/hyperfine/options.rs-107 removed
1use super::units::{Second, Unit};23#[cfg(not(windows))]4pub const DEFAULT_SHELL: &str = "sh";56#[cfg(windows)]7pub const DEFAULT_SHELL: &str = "cmd.exe";89/// Action to take when an executed command fails.10#[derive(Debug, Clone, Copy, PartialEq)]11pub enum CmdFailureAction {12 /// Exit with an error message13 RaiseError,1415 /// Simply ignore the non-zero exit code16 Ignore,17}1819/// Output style type option20#[derive(Debug, Clone, Copy, PartialEq)]21pub enum OutputStyleOption {22 /// Do not output with colors or any special formatting23 Basic,2425 /// Output with full color and formatting26 Full,2728 /// Keep elements such as progress bar, but use no coloring29 NoColor,3031 /// Keep coloring, but use no progress bar32 Color,3334 /// Disable all the output35 Disabled,36}3738/// Number of runs for a benchmark39pub struct Runs {40 /// Minimum number of benchmark runs41 pub min: u64,4243 /// Maximum number of benchmark runs44 pub max: Option<u64>,45}4647impl Default for Runs {48 fn default() -> Runs {49 Runs { min: 10, max: None }50 }51}5253/// A set of options for hyperfine54pub struct HyperfineOptions {55 /// Number of warmup runs56 pub warmup_count: u64,5758 /// Number of benchmark runs59 pub runs: Runs,6061 /// Minimum benchmarking time62 pub min_time_sec: Second,6364 /// Whether or not to ignore non-zero exit codes65 pub failure_action: CmdFailureAction,6667 /// Command to run before each timing run68 pub preparation_command: Option<Vec<String>>,6970 /// Command to run after each benchmark71 pub cleanup_command: Option<String>,7273 /// What color mode to use for output74 pub output_style: OutputStyleOption,7576 /// The shell to use for executing commands.77 pub shell: String,7879 /// Forward benchmark's stdout to hyperfine's stdout80 pub show_output: bool,8182 /// Which time unit to use for CLI & Markdown output83 pub time_unit: Option<Unit>,8485 /// 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}9091impl 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.7use statistical::median;89/// 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.12pub const OUTLIER_THRESHOLD: f64 = 1.4826 * 10.0;1314/// 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>20pub fn modified_zscores(xs: &[f64]) -> Vec<f64> {21 assert!(!xs.is_empty());2223 // Compute sample median:24 let x_median = median(xs);2526 // Compute the absolute deviations from the median:27 let deviations: Vec<f64> = xs.iter().map(|x| (x - x_median).abs()).collect();2829 // Compute median absolute deviation:30 let mad = median(&deviations);3132 // Handle MAD == 0 case33 let mad = if mad > 0.0 { mad } else { f64::EPSILON };3435 // Compute modified Z-scores (x_i - x_median) / MAD36 xs.iter().map(|&x| (x - x_median) / mad).collect()37}3839/// 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)]42pub fn num_outliers(xs: &[f64]) -> usize {43 if xs.is_empty() {44 return 0;45 }4647 let scores = modified_zscores(xs);48 scores49 .iter()50 .filter(|&&s| s.abs() > OUTLIER_THRESHOLD)51 .count()52}5354#[test]55fn 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]));6061 // Should not detect outliers in low-variance samples62 let xs = [-0.2, 0.0, 0.2];63 assert_eq!(0, num_outliers(&xs));6465 // Should detect a single outlier66 let xs = [-0.2, 0.0, 0.2, 4.0];67 assert_eq!(1, num_outliers(&xs));6869 // Should detect a single outlier70 let xs = [0.5, 0.30, 0.29, 0.31, 0.30];71 assert_eq!(1, num_outliers(&xs));7273 // 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));8788 // 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}105106#[test]107fn 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));111112 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
1use std::convert::TryInto;2use std::ops::{Add, AddAssign, Div, Sub};3use std::str::FromStr;45use clap::Values;6use rust_decimal::Decimal;78use crate::hyperfine::command::Command;9use crate::hyperfine::error::ParameterScanError;10use crate::hyperfine::types::{NumericType, ParameterValue};1112trait 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}24impl<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}3738#[derive(Debug)]39struct RangeStep<T> {40 state: T,41 end: T,42 step: T,43}4445impl<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 }5051 if step == T::from(0) {52 return Err(ParameterScanError::ZeroStep);53 }5455 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}6667impl<T: Numeric> Iterator for RangeStep<T> {68 type Item = T;6970 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;7677 Some(return_val)78 }7980 fn size_hint(&self) -> (usize, Option<usize>) {81 range_step_size_hint(self.state, self.end, self.step)82 }83}8485fn 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 }8990 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}9697fn 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();108109 // `--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 }117118 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}136137pub 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();148149 // 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 }164165 // try parsing them as decimals166 let param_min = Decimal::from_str(param_min)?;167 let param_max = Decimal::from_str(param_max)?;168169 if step.is_none() {170 return Err(ParameterScanError::StepRequired);171 }172173 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}183184#[test]185fn test_integer_range() {186 let param_range: Vec<i32> = RangeStep::new(0, 10, 3).unwrap().collect();187188 assert_eq!(param_range.len(), 4);189 assert_eq!(param_range[0], 0);190 assert_eq!(param_range[3], 9);191}192193#[test]194fn 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();198199 let param_range: Vec<Decimal> = RangeStep::new(param_min, param_max, step)200 .unwrap()201 .collect();202203 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}207208#[test]209fn test_range_step_validate() {210 let result = RangeStep::new(0, 10, 3);211 assert!(result.is_ok());212213 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());219220 let result = RangeStep::new(11, 10, 1);221 assert_eq!(format!("{}", result.unwrap_err()), "Empty parameter range");222223 let result = RangeStep::new(0, 10, 0);224 assert_eq!(225 format!("{}", result.unwrap_err()),226 "Zero is not a valid parameter step"227 );228229 let result = RangeStep::new(0, 100_001, 1);230 assert_eq!(231 format!("{}", result.unwrap_err()),232 "Parameter range is too large"233 );234}235236#[test]237fn 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}244245#[test]246fn 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();250251 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}264265#[test]266fn 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}283284#[test]285fn 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}302303#[test]304fn 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
1use std::io;2use std::process::{Command, ExitStatus, Stdio};34use crate::hyperfine::timer::get_cpu_timer;56/// Used to indicate the result of running a command7#[derive(Debug, Copy, Clone)]8pub struct ExecuteResult {9 /// The amount of user time the process used10 pub user_time: f64,1112 /// The amount of cpu time the process used13 pub system_time: f64,1415 /// The exit status of the process16 pub status: ExitStatus,17}1819/// Execute the given command and return a timing summary20#[cfg(windows)]21pub 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()?;3031 let (user_time, system_time) = cpu_timer.stop();32 Ok(ExecuteResult {33 user_time,34 system_time,35 status,36 })37}3839/// Execute the given command and return a timing summary40#[cfg(not(windows))]41pub 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();4849 let status = run_shell_command(stdout, stderr, command, shell)?;5051 let (user_time, system_time) = cpu_timer.stop();5253 Ok(ExecuteResult {54 user_time,55 system_time,56 status,57 })58}5960/// Run a standard shell command using `sh -c`61#[cfg(not(windows))]62fn 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}8081/// Run a Windows shell command using `cmd.exe /C`82#[cfg(windows)]83fn 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
1use serde::Serialize;2use std::convert::TryFrom;3use std::fmt;45use rust_decimal::prelude::ToPrimitive;6use rust_decimal::Decimal;78#[derive(Debug, Clone, Serialize, Copy, PartialEq, Eq)]9#[serde(untagged)]10pub enum NumericType {11 Int(i32),12 Decimal(Decimal),13}1415impl 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}2324impl From<i32> for NumericType {25 fn from(x: i32) -> NumericType {26 NumericType::Int(x)27 }28}2930impl From<Decimal> for NumericType {31 fn from(x: Decimal) -> NumericType {32 NumericType::Decimal(x)33 }34}3536impl TryFrom<NumericType> for usize {37 type Error = ();3839 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}4950#[derive(Debug, Clone, PartialEq, Eq)]51pub enum ParameterValue {52 Text(String),53 Numeric(NumericType),54}5556impl<'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.23pub type Scalar = f64;45/// Type alias for unit of time6pub type Second = Scalar;78/// Supported time units9#[derive(Debug, Clone, Copy, PartialEq)]10pub enum Unit {11 Second,12 MilliSecond,13}1415impl 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 }2324 /// 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}3233#[test]34fn test_unit_short_name() {35 assert_eq!("s", Unit::Second.short_name());36 assert_eq!("ms", Unit::MilliSecond.short_name());37}3839// Note - the values are rounded when formatted.40#[test]41fn 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
1use std::fmt;23use crate::hyperfine::format::format_duration;4use crate::hyperfine::internal::MIN_EXECUTION_TIME;5use crate::hyperfine::units::Second;67/// A list of all possible warnings8pub enum Warnings {9 FastExecutionTime,10 NonZeroExitCode,11 SlowInitialRun(Second),12 OutliersDetected,13}1415impl 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
1use crate::units::Second;23#[derive(Debug, Copy, Clone)]4pub struct CPUTimes {5 /// Total amount of time spent executing in user mode6 pub user_usec: i64,78 /// Total amount of time spent executing in kernel mode9 pub system_usec: i64,10}1112#[derive(Debug, Copy, Clone)]13pub struct CPUInterval {14 /// Total amount of time spent executing in user mode15 pub user: Second,1617 /// Total amount of time spent executing in kernel mode18 pub system: Second,19}
added:src/timer/mod.rs+28 added
1mod internal;23pub mod wallclocktimer;45use cfg_if::cfg_if;67cfg_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}16use std::process::Child;1718/// Defines start functionality of a timer.19pub trait TimerStart {20 fn start() -> Self;21 fn start_for_process(process: &Child) -> Self;22}2324/// Defines stop functionality of a timer.25pub trait TimerStop {26 type Result;27 fn stop(&self) -> Self::Result;28}
added:src/timer/unix_timer.rs+96 added
1#![cfg(not(windows))]23use super::internal::{CPUInterval, CPUTimes};4use crate::timer::{TimerStart, TimerStop};5use crate::units::Second;67use std::mem;8use std::process::Child;910pub fn get_cpu_timer() -> Box<dyn TimerStop<Result = (Second, Second)>> {11 Box::new(CPUTimer::start())12}1314struct CPUTimer {15 start_cpu: CPUTimes,16}1718impl TimerStart for CPUTimer {19 fn start() -> Self {20 CPUTimer {21 start_cpu: get_cpu_times(),22 }23 }2425 fn start_for_process(_: &Child) -> Self {26 Self::start()27 }28}2930impl TimerStop for CPUTimer {31 type Result = (Second, Second);3233 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}3940/// Read CPU execution times ('user' and 'system')41fn get_cpu_times() -> CPUTimes {42 use libc::{getrusage, rusage, RUSAGE_CHILDREN};4344 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 };5051 const MICROSEC_PER_SEC: i64 = 1000 * 1000;5253 #[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}6162/// Compute the time intervals in between two `CPUTimes` snapshots63fn 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}6970#[cfg(test)]71use approx::assert_relative_eq;7273#[test]74fn test_cpu_time_interval() {75 let t_a = CPUTimes {76 user_usec: 12345,77 system_usec: 54321,78 };7980 let t_b = CPUTimes {81 user_usec: 20000,82 system_usec: 70000,83 };8485 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);8889 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);9293 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
1use std::process::Child;2use std::time::Instant;34use crate::timer::{TimerStart, TimerStop};5use crate::units::Second;67pub struct WallClockTimer {8 start: Instant,9}1011impl TimerStart for WallClockTimer {12 fn start() -> WallClockTimer {13 WallClockTimer {14 start: Instant::now(),15 }16 }1718 fn start_for_process(_: &Child) -> Self {19 Self::start()20 }21}2223impl TimerStop for WallClockTimer {24 type Result = Second;2526 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)]23use super::internal::CPUTimes;4use crate::timer::{TimerStart, TimerStop};5use crate::units::Second;67use winapi::um::processthreadsapi::GetProcessTimes;8use winapi::um::winnt::HANDLE;910use std::mem;11use std::os::windows::io::{AsRawHandle, RawHandle};12use std::process::Child;1314const HUNDRED_NS_PER_MS: i64 = 10;1516pub fn get_cpu_timer(process: &Child) -> Box<dyn TimerStop<Result = (Second, Second)>> {17 Box::new(CPUTimer::start_for_process(process))18}1920struct CPUTimer {21 handle: RawHandle,22}2324impl TimerStart for CPUTimer {25 fn start() -> Self {26 panic!()27 }2829 fn start_for_process(process: &Child) -> Self {30 CPUTimer {31 handle: process.as_raw_handle(),32 }33 }34}3536impl TimerStop for CPUTimer {37 type Result = (Second, Second);3839 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}4748/// Read CPU execution times (dummy for now)49fn 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 );6263 // 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 };7879 CPUTimes {80 user_usec,81 system_usec,82 }83}
added:src/app.rs+242 added
1use atty::Stream;2use clap::{crate_version, App, AppSettings, Arg, ArgMatches};3use std::ffi::OsString;45pub fn get_arg_matches<I, T>(args: I) -> ArgMatches<'static>6where7 I: IntoIterator<Item = T>,8 T: Into<OsString> + Clone,9{10 let app = build_app();11 app.get_matches_from(args)12}1314/// Build the clap app for parsing command line arguments15fn build_app() -> App<'static, 'static> {16 let clap_color_setting = if atty::is(Stream::Stdout) {17 AppSettings::ColoredHelp18 } else {19 AppSettings::ColorNever20 };2122 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
1use serde::Serialize;2use std::collections::BTreeMap;34use crate::units::Second;56/// 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)]10pub struct BenchmarkResult {11 /// The command that was run12 pub command: String,1314 /// The mean run time15 pub mean: Second,1617 /// The standard deviation of all run times18 pub stddev: Second,1920 /// The median run time21 pub median: Second,2223 /// Time spend in user space24 pub user: Second,2526 /// Time spent in system space27 pub system: Second,2829 /// Min time measured30 pub min: Second,3132 /// Max time measured33 pub max: Second,3435 /// All run time measurements36 #[serde(skip_serializing_if = "Option::is_none")]37 pub times: Option<Vec<Second>>,3839 /// All run exit codes40 pub exit_codes: Vec<Option<i32>>,4142 /// Any parameter values used43 #[serde(skip_serializing_if = "BTreeMap::is_empty")]44 pub parameters: BTreeMap<String, String>,45}4647impl 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
1use std::cmp;2use std::io;3use std::process::{ExitStatus, Stdio};45use colored::*;6use statistical::{mean, median, standard_deviation};78use crate::benchmark_result::BenchmarkResult;9use crate::command::Command;10use crate::format::{format_duration, format_duration_unit};11use crate::internal::{get_progress_bar, max, min, MIN_EXECUTION_TIME};12use crate::options::{CmdFailureAction, HyperfineOptions, OutputStyleOption};13use crate::outlier_detection::{modified_zscores, OUTLIER_THRESHOLD};14use crate::shell::execute_and_time;15use crate::timer::wallclocktimer::WallClockTimer;16use crate::timer::{TimerStart, TimerStop};17use crate::units::Second;18use crate::warnings::Warnings;1920/// Results from timing a single shell command21#[derive(Debug, Default, Copy, Clone)]22pub struct TimingResult {23 /// Wall clock time24 pub time_real: Second,2526 /// Time spent in user mode27 pub time_user: Second,2829 /// Time spent in kernel mode30 pub time_system: Second,31}3233/// Correct for shell spawning time34fn 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}4142/// Run the given shell command and measure the execution time43pub 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 };5556 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();5960 let mut time_user = result.user_time;61 let mut time_system = result.system_time;6263 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 }7778 // 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 }8485 Ok((86 TimingResult {87 time_real,88 time_user,89 time_system,90 },91 result.status,92 ))93}9495/// Measure the average shell spawning time96pub 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 };111112 let mut times_real: Vec<Second> = vec![];113 let mut times_user: Vec<Second> = vec![];114 let mut times_system: Vec<Second> = vec![];115116 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 );125126 match res {127 Err(_) => {128 let shell_cmd = if cfg!(windows) {129 format!("{} /C \"\"", shell)130 } else {131 format!("{} -c \"\"", shell)132 };133134 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 }149150 if let Some(bar) = progress_bar.as_ref() {151 bar.inc(1)152 }153 }154155 if let Some(bar) = progress_bar.as_ref() {156 bar.finish_and_clear()157 }158159 Ok(TimingResult {160 time_real: mean(&times_real),161 time_user: mean(&times_user),162 time_system: mean(&times_system),163 })164}165166fn 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}183184/// Run the command specified by `--prepare`.185fn 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.";192193 run_intermediate_command(shell, command, show_output, error_output)194}195196/// Run the command specified by `--cleanup`.197fn 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.";204205 run_intermediate_command(shell, command, show_output, error_output)206}207208#[cfg(unix)]209fn extract_exit_code(status: ExitStatus) -> Option<i32> {210 use std::os::unix::process::ExitStatusExt;211212 /* 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}223224#[cfg(not(unix))]225fn extract_exit_code(status: ExitStatus) -> Option<i32> {226 status.code()227}228229/// Run the benchmark for a single shell command230pub 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 }245246 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;251252 // 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 });261262 // 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 };273274 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 }291292 // 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 };302303 let prepare_res = run_preparation_command(&options.shell, &prepare_cmd, options.show_output)?;304305 // 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();314315 // 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;319320 let count = {321 let min = cmp::max(runs_in_min_time, options.runs.min);322323 options324 .runs325 .max326 .as_ref()327 .map(|max| cmp::min(min, *max))328 .unwrap_or(min)329 };330331 let count_remaining = count - 1;332333 // 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));338339 all_succeeded = all_succeeded && success;340341 // 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 }348349 // Gather statistics350 for _ in 0..count_remaining {351 run_preparation_command(&options.shell, &prepare_cmd, options.show_output)?;352353 let msg = {354 let mean = format_duration(mean(&times_real), options.time_unit);355 format!("Current estimate: {}", mean.to_string().green())356 };357358 if let Some(bar) = progress_bar.as_ref() {359 bar.set_message(msg.to_owned())360 }361362 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();370371 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));375376 all_succeeded = all_succeeded && success;377378 if let Some(bar) = progress_bar.as_ref() {379 bar.inc(1)380 }381 }382383 if let Some(bar) = progress_bar.as_ref() {384 bar.finish_and_clear()385 }386387 // Compute statistical quantities388 let t_num = times_real.len();389 let t_mean = mean(&times_real);390 let t_stddev = standard_deviation(&times_real, Some(t_mean));391 let t_median = median(&times_real);392 let t_min = min(&times_real);393 let t_max = max(&times_real);394395 let user_mean = mean(&times_user);396 let system_mean = mean(&times_system);397398 // 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);404405 let user_str = format_duration(user_mean, Some(time_unit));406 let system_str = format_duration(system_mean, Some(time_unit));407408 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 );418419 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 }428429 // Warnings430 let mut warnings = vec![];431432 // Check execution time433 if times_real.iter().any(|&t| t < MIN_EXECUTION_TIME) {434 warnings.push(Warnings::FastExecutionTime);435 }436437 // Check programm exit codes438 if !all_succeeded {439 warnings.push(Warnings::NonZeroExitCode);440 }441442 // Run outlier detection443 let scores = modified_zscores(&times_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 }449450 if !warnings.is_empty() {451 eprintln!(" ");452453 for warning in &warnings {454 eprintln!(" {}: {}", "Warning".yellow(), warning);455 }456 }457458 if options.output_style != OutputStyleOption::Disabled {459 println!(" ");460 }461462 // 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)?;467468 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
1use std::collections::BTreeMap;2use std::fmt;34use super::types::ParameterValue;56/// A command that should be benchmarked.7#[derive(Debug, Clone, PartialEq, Eq)]8pub struct Command<'a> {9 /// The command name (without parameter substitution)10 name: Option<&'a str>,1112 /// The command that should be executed (without parameter substitution)13 expression: &'a str,1415 /// Zero or more parameter values.16 parameters: Vec<(&'a str, ParameterValue)>,17}1819impl<'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 }2728 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 }3940 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 }4647 pub fn get_shell_command(&self) -> String {48 self.replace_parameters_in(self.expression)49 }5051 pub fn get_parameters(&self) -> &Vec<(&'a str, ParameterValue)> {52 &self.parameters53 }5455 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}8485#[test]86fn 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}9798#[test]99fn 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}110111impl<'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
1use rust_decimal::Error as DecimalError;2use std::error::Error;3use std::fmt;4use std::num;5use std::num::ParseIntError;67#[derive(Debug)]8pub enum ParameterScanError {9 ParseIntError(num::ParseIntError),10 ParseDecimalError(DecimalError),11 EmptyRange,12 TooLarge,13 ZeroStep,14 StepRequired,15 UnexpectedCommandNameCount(usize, usize),16}1718impl From<num::ParseIntError> for ParameterScanError {19 fn from(e: num::ParseIntError) -> ParameterScanError {20 ParameterScanError::ParseIntError(e)21 }22}2324impl From<DecimalError> for ParameterScanError {25 fn from(e: DecimalError) -> ParameterScanError {26 ParameterScanError::ParseDecimalError(e)27 }28}2930impl 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}5455impl Error for ParameterScanError {}5657#[derive(Debug)]58pub enum OptionsError<'a> {59 RunsBelowTwo,60 EmptyRunsRange,61 TooManyCommandNames(usize),62 UnexpectedCommandNameCount(usize, usize),63 NumericParsingError(&'a str, ParseIntError),64}6566impl<'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}9091impl<'a> Error for OptionsError<'a> {}
added:src/format.rs+65 added
1use crate::units::{Second, Unit};23/// 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.5pub fn format_duration(duration: Second, unit: Option<Unit>) -> String {6 let (duration_fmt, _) = format_duration_unit(duration, unit);7 duration_fmt8}910/// Like `format_duration`, but returns the target unit as well.11pub fn format_duration_unit(duration: Second, unit: Option<Unit>) -> (String, Unit) {12 let (out_str, out_unit) = format_duration_value(duration, unit);1314 (format!("{} {}", out_str, out_unit.short_name()), out_unit)15}1617/// Like `format_duration`, but returns the target unit as well.18pub 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}2526#[test]27fn test_format_duration_unit_basic() {28 let (out_str, out_unit) = format_duration_unit(1.3, None);2930 assert_eq!("1.300 s", out_str);31 assert_eq!(Unit::Second, out_unit);3233 let (out_str, out_unit) = format_duration_unit(1.0, None);3435 assert_eq!("1.000 s", out_str);36 assert_eq!(Unit::Second, out_unit);3738 let (out_str, out_unit) = format_duration_unit(0.999, None);3940 assert_eq!("999.0 ms", out_str);41 assert_eq!(Unit::MilliSecond, out_unit);4243 let (out_str, out_unit) = format_duration_unit(0.0, None);4445 assert_eq!("0.0 ms", out_str);46 assert_eq!(Unit::MilliSecond, out_unit);4748 let (out_str, out_unit) = format_duration_unit(1000.0, None);4950 assert_eq!("1000.000 s", out_str);51 assert_eq!(Unit::Second, out_unit);52}5354#[test]55fn test_format_duration_unit_with_unit() {56 let (out_str, out_unit) = format_duration_unit(1.3, Some(Unit::Second));5758 assert_eq!("1.300 s", out_str);59 assert_eq!(Unit::Second, out_unit);6061 let (out_str, out_unit) = format_duration_unit(1.3, Some(Unit::MilliSecond));6263 assert_eq!("1300.0 ms", out_str);64 assert_eq!(Unit::MilliSecond, out_unit);65}
added:src/internal.rs+255 added
1use colored::*;2use indicatif::{ProgressBar, ProgressStyle};34use crate::benchmark_result::BenchmarkResult;5use crate::options::OutputStyleOption;6use crate::units::{Scalar, Second};78use std::cmp::Ordering;9use std::iter::Iterator;1011/// Threshold for warning about fast execution time12pub const MIN_EXECUTION_TIME: Second = 5e-3;1314#[cfg(not(windows))]15const TICK_SETTINGS: (&str, u64) = ("⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏ ", 80);1617#[cfg(windows)]18const TICK_SETTINGS: (&str, u64) = (r"+-x| ", 200);1920/// Return a pre-configured progress bar21pub 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 };2829 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());3637 progress_bar38}3940/// A max function for f64's without NaNs41pub fn max(vals: &[f64]) -> f64 {42 *vals43 .iter()44 .max_by(|a, b| a.partial_cmp(b).unwrap())45 .unwrap()46}4748/// A min function for f64's without NaNs49pub fn min(vals: &[f64]) -> f64 {50 *vals51 .iter()52 .min_by(|a, b| a.partial_cmp(b).unwrap())53 .unwrap()54}5556#[derive(Debug)]57pub 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}6364fn compare_mean_time(l: &BenchmarkResult, r: &BenchmarkResult) -> Ordering {65 l.mean.partial_cmp(&r.mean).unwrap_or(Ordering::Equal)66}6768pub 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");7576 if fastest.mean == 0.0 {77 return None;78 }7980 Some(81 results82 .iter()83 .map(|result| {84 let ratio = result.mean / fastest.mean;8586 // 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();9293 BenchmarkResultWithRelativeSpeed {94 result,95 relative_speed: ratio,96 relative_speed_stddev: ratio_stddev,97 is_fastest: result == fastest,98 }99 })100 .collect(),101 )102}103104pub fn write_benchmark_comparison(results: &[BenchmarkResult]) {105 if results.len() < 2 {106 return;107 }108109 if let Some(mut annotated_results) = compute_relative_speed(results) {110 annotated_results.sort_by(|l, r| compare_mean_time(l.result, r.result));111112 let fastest = &annotated_results[0];113 let others = &annotated_results[1..];114115 println!("{}", "Summary".bold());116 println!(" '{}' ran", fastest.result.command.cyan());117118 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}137138#[test]139fn test_max() {140 let assert_float_eq = |a, b| {141 assert!((a - b) < f64::EPSILON);142 };143144 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}150151#[cfg(test)]152fn create_result(name: &str, mean: Scalar) -> BenchmarkResult {153 use std::collections::BTreeMap;154155 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}169170#[test]171fn test_compute_relative_speed() {172 use approx::assert_relative_eq;173174 let results = vec![175 create_result("cmd1", 3.0),176 create_result("cmd2", 2.0),177 create_result("cmd3", 5.0),178 ];179180 let annotated_results = compute_relative_speed(&results).unwrap();181182 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}186187#[test]188fn test_compute_relative_speed_for_zero_times() {189 let results = vec![create_result("cmd1", 1.0), create_result("cmd2", 0.0)];190191 let annotated_results = compute_relative_speed(&results);192193 assert!(annotated_results.is_none());194}195196pub fn tokenize(values: &str) -> Vec<String> {197 let mut tokens = vec![];198 let mut buf = String::new();199200 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 }222223 tokens.push(buf);224225 tokens226}227228#[test]229fn 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}240241#[test]242fn 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"]);245246 assert_eq!(tokenize(r"hello\,world!,baz"), vec!["hello,world!", "baz"]);247}248249#[test]250fn 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 lines
6use atty::Stream;7use clap::ArgMatches;8use colored::*;910mod hyperfine;10pub mod app;11pub mod benchmark;12pub mod benchmark_result;13pub mod command;14pub mod error;15pub mod export;16pub mod format;17pub mod internal;18pub mod options;19pub mod outlier_detection;20pub mod parameter_range;21pub mod shell;22pub mod timer;23pub mod types;24pub mod units;25pub mod warnings;2612use crate::hyperfine::app::get_arg_matches;13use crate::hyperfine::benchmark::{mean_shell_spawning_time, run_benchmark};14use crate::hyperfine::command::Command;15use crate::hyperfine::error::OptionsError;16use crate::hyperfine::export::{ExportManager, ExportType};17use crate::hyperfine::internal::{tokenize, write_benchmark_comparison};18use crate::hyperfine::options::{CmdFailureAction, HyperfineOptions, OutputStyleOption};19use crate::hyperfine::parameter_range::get_parameterized_commands;20use crate::hyperfine::types::ParameterValue;21use crate::hyperfine::units::Unit;27use app::get_arg_matches;28use benchmark::{mean_shell_spawning_time, run_benchmark};29use command::Command;30use error::OptionsError;31use export::{ExportManager, ExportType};32use internal::{tokenize, write_benchmark_comparison};33use options::{CmdFailureAction, HyperfineOptions, OutputStyleOption};34use parameter_range::get_parameterized_commands;35use types::ParameterValue;36use units::Unit;3738/// Print error message to stderr and terminate39pub fn error(message: &str) -> ! {40 eprintln!("{} {}", "Error:".red(), message);
382 unmodified lines
added:src/options.rs+107 added
1use super::units::{Second, Unit};23#[cfg(not(windows))]4pub const DEFAULT_SHELL: &str = "sh";56#[cfg(windows)]7pub const DEFAULT_SHELL: &str = "cmd.exe";89/// Action to take when an executed command fails.10#[derive(Debug, Clone, Copy, PartialEq)]11pub enum CmdFailureAction {12 /// Exit with an error message13 RaiseError,1415 /// Simply ignore the non-zero exit code16 Ignore,17}1819/// Output style type option20#[derive(Debug, Clone, Copy, PartialEq)]21pub enum OutputStyleOption {22 /// Do not output with colors or any special formatting23 Basic,2425 /// Output with full color and formatting26 Full,2728 /// Keep elements such as progress bar, but use no coloring29 NoColor,3031 /// Keep coloring, but use no progress bar32 Color,3334 /// Disable all the output35 Disabled,36}3738/// Number of runs for a benchmark39pub struct Runs {40 /// Minimum number of benchmark runs41 pub min: u64,4243 /// Maximum number of benchmark runs44 pub max: Option<u64>,45}4647impl Default for Runs {48 fn default() -> Runs {49 Runs { min: 10, max: None }50 }51}5253/// A set of options for hyperfine54pub struct HyperfineOptions {55 /// Number of warmup runs56 pub warmup_count: u64,5758 /// Number of benchmark runs59 pub runs: Runs,6061 /// Minimum benchmarking time62 pub min_time_sec: Second,6364 /// Whether or not to ignore non-zero exit codes65 pub failure_action: CmdFailureAction,6667 /// Command to run before each timing run68 pub preparation_command: Option<Vec<String>>,6970 /// Command to run after each benchmark71 pub cleanup_command: Option<String>,7273 /// What color mode to use for output74 pub output_style: OutputStyleOption,7576 /// The shell to use for executing commands.77 pub shell: String,7879 /// Forward benchmark's stdout to hyperfine's stdout80 pub show_output: bool,8182 /// Which time unit to use for CLI & Markdown output83 pub time_unit: Option<Unit>,8485 /// 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}9091impl 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.7use statistical::median;89/// 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.12pub const OUTLIER_THRESHOLD: f64 = 1.4826 * 10.0;1314/// 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>20pub fn modified_zscores(xs: &[f64]) -> Vec<f64> {21 assert!(!xs.is_empty());2223 // Compute sample median:24 let x_median = median(xs);2526 // Compute the absolute deviations from the median:27 let deviations: Vec<f64> = xs.iter().map(|x| (x - x_median).abs()).collect();2829 // Compute median absolute deviation:30 let mad = median(&deviations);3132 // Handle MAD == 0 case33 let mad = if mad > 0.0 { mad } else { f64::EPSILON };3435 // Compute modified Z-scores (x_i - x_median) / MAD36 xs.iter().map(|&x| (x - x_median) / mad).collect()37}3839/// 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)]42pub fn num_outliers(xs: &[f64]) -> usize {43 if xs.is_empty() {44 return 0;45 }4647 let scores = modified_zscores(xs);48 scores49 .iter()50 .filter(|&&s| s.abs() > OUTLIER_THRESHOLD)51 .count()52}5354#[test]55fn 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]));6061 // Should not detect outliers in low-variance samples62 let xs = [-0.2, 0.0, 0.2];63 assert_eq!(0, num_outliers(&xs));6465 // Should detect a single outlier66 let xs = [-0.2, 0.0, 0.2, 4.0];67 assert_eq!(1, num_outliers(&xs));6869 // Should detect a single outlier70 let xs = [0.5, 0.30, 0.29, 0.31, 0.30];71 assert_eq!(1, num_outliers(&xs));7273 // 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));8788 // 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}105106#[test]107fn 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));111112 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
1use std::convert::TryInto;2use std::ops::{Add, AddAssign, Div, Sub};3use std::str::FromStr;45use clap::Values;6use rust_decimal::Decimal;78use crate::command::Command;9use crate::error::ParameterScanError;10use crate::types::{NumericType, ParameterValue};1112trait 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}24impl<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}3738#[derive(Debug)]39struct RangeStep<T> {40 state: T,41 end: T,42 step: T,43}4445impl<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 }5051 if step == T::from(0) {52 return Err(ParameterScanError::ZeroStep);53 }5455 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}6667impl<T: Numeric> Iterator for RangeStep<T> {68 type Item = T;6970 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;7677 Some(return_val)78 }7980 fn size_hint(&self) -> (usize, Option<usize>) {81 range_step_size_hint(self.state, self.end, self.step)82 }83}8485fn 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 }8990 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}9697fn 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();108109 // `--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 }117118 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}136137pub 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();148149 // 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 }164165 // try parsing them as decimals166 let param_min = Decimal::from_str(param_min)?;167 let param_max = Decimal::from_str(param_max)?;168169 if step.is_none() {170 return Err(ParameterScanError::StepRequired);171 }172173 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}183184#[test]185fn test_integer_range() {186 let param_range: Vec<i32> = RangeStep::new(0, 10, 3).unwrap().collect();187188 assert_eq!(param_range.len(), 4);189 assert_eq!(param_range[0], 0);190 assert_eq!(param_range[3], 9);191}192193#[test]194fn 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();198199 let param_range: Vec<Decimal> = RangeStep::new(param_min, param_max, step)200 .unwrap()201 .collect();202203 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}207208#[test]209fn test_range_step_validate() {210 let result = RangeStep::new(0, 10, 3);211 assert!(result.is_ok());212213 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());219220 let result = RangeStep::new(11, 10, 1);221 assert_eq!(format!("{}", result.unwrap_err()), "Empty parameter range");222223 let result = RangeStep::new(0, 10, 0);224 assert_eq!(225 format!("{}", result.unwrap_err()),226 "Zero is not a valid parameter step"227 );228229 let result = RangeStep::new(0, 100_001, 1);230 assert_eq!(231 format!("{}", result.unwrap_err()),232 "Parameter range is too large"233 );234}235236#[test]237fn 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}244245#[test]246fn 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();250251 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}264265#[test]266fn 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}283284#[test]285fn 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}302303#[test]304fn 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
1use std::io;2use std::process::{Command, ExitStatus, Stdio};34use crate::timer::get_cpu_timer;56/// Used to indicate the result of running a command7#[derive(Debug, Copy, Clone)]8pub struct ExecuteResult {9 /// The amount of user time the process used10 pub user_time: f64,1112 /// The amount of cpu time the process used13 pub system_time: f64,1415 /// The exit status of the process16 pub status: ExitStatus,17}1819/// Execute the given command and return a timing summary20#[cfg(windows)]21pub 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()?;3031 let (user_time, system_time) = cpu_timer.stop();32 Ok(ExecuteResult {33 user_time,34 system_time,35 status,36 })37}3839/// Execute the given command and return a timing summary40#[cfg(not(windows))]41pub 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();4849 let status = run_shell_command(stdout, stderr, command, shell)?;5051 let (user_time, system_time) = cpu_timer.stop();5253 Ok(ExecuteResult {54 user_time,55 system_time,56 status,57 })58}5960/// Run a standard shell command using `sh -c`61#[cfg(not(windows))]62fn 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}8081/// Run a Windows shell command using `cmd.exe /C`82#[cfg(windows)]83fn 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
1use serde::Serialize;2use std::convert::TryFrom;3use std::fmt;45use rust_decimal::prelude::ToPrimitive;6use rust_decimal::Decimal;78#[derive(Debug, Clone, Serialize, Copy, PartialEq, Eq)]9#[serde(untagged)]10pub enum NumericType {11 Int(i32),12 Decimal(Decimal),13}1415impl 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}2324impl From<i32> for NumericType {25 fn from(x: i32) -> NumericType {26 NumericType::Int(x)27 }28}2930impl From<Decimal> for NumericType {31 fn from(x: Decimal) -> NumericType {32 NumericType::Decimal(x)33 }34}3536impl TryFrom<NumericType> for usize {37 type Error = ();3839 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}4950#[derive(Debug, Clone, PartialEq, Eq)]51pub enum ParameterValue {52 Text(String),53 Numeric(NumericType),54}5556impl<'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.23pub type Scalar = f64;45/// Type alias for unit of time6pub type Second = Scalar;78/// Supported time units9#[derive(Debug, Clone, Copy, PartialEq)]10pub enum Unit {11 Second,12 MilliSecond,13}1415impl 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 }2324 /// 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}3233#[test]34fn test_unit_short_name() {35 assert_eq!("s", Unit::Second.short_name());36 assert_eq!("ms", Unit::MilliSecond.short_name());37}3839// Note - the values are rounded when formatted.40#[test]41fn 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
1use std::fmt;23use crate::format::format_duration;4use crate::internal::MIN_EXECUTION_TIME;5use crate::units::Second;67/// A list of all possible warnings8pub enum Warnings {9 FastExecutionTime,10 NonZeroExitCode,11 SlowInitialRun(Second),12 OutliersDetected,13}1415impl 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
1use std::fs;23use clap::Shell;45include!("src/hyperfine/app.rs");5include!("src/app.rs");67fn main() {8 let min_version = "1.39";9
22 unmodified lines