Add option to set time units for CLI & Markdown, closes #80
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Add option to set the time units to either `MilliSecond` or `Second` for both CLI output and Markdown export, overriding the default logic.
authored by Jason Peacock · committed by David Peter · parent 1ec810f · Browse files · 9 files·+172 added−67 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
9 files+172 added−67 removed
- other:+172 added−67 removed
Provenance
- Commit
f0b6f13- Tree
0b276c0- Author
Jason Peacock <jason@jasonpeacock.com>- Committer
David Peter <sharkdp@users.noreply.github.com>- Parent
1ec810f
9 files changed+172 added−67 removed
modified:src/hyperfine/export/csv.rs+3 added-3 removed
1 use super::Exporter;2 3-use hyperfine::types::BenchmarkResult;3+use hyperfine::types::{BenchmarkResult, Unit};4 5 use std::io::{Error, ErrorKind, Result};6 7 use csv::WriterBuilder;1 unmodified line9 #[derive(Default)]10 pub struct CsvExporter {}11 12 impl Exporter for CsvExporter {13- fn serialize(&self, results: &Vec<BenchmarkResult>) -> Result<Vec<u8>> {13+ fn serialize(&self, results: &Vec<BenchmarkResult>, _unit: Option<Unit>) -> Result<Vec<u8>> {14 let mut writer = WriterBuilder::new().from_writer(vec![]);15 for res in results {16- // The list of times can not be exported to the CSV file - remove it:16+ // The list of times cannot be exported to the CSV file - remove it:17 let mut result = res.clone();18 result.times = None;19 20 writer.serialize(result)?;7 unmodified linesmodified:src/hyperfine/export/json.rs+2 added-2 removed
1 use super::Exporter;2-use hyperfine::types::BenchmarkResult;2+use hyperfine::types::{BenchmarkResult, Unit};3 4 use std::io::{Error, ErrorKind, Result};5 6 use serde_json::to_vec_pretty;6 unmodified lines13 #[derive(Default)]14 pub struct JsonExporter {}15 16 impl Exporter for JsonExporter {17- fn serialize(&self, results: &Vec<BenchmarkResult>) -> Result<Vec<u8>> {17+ fn serialize(&self, results: &Vec<BenchmarkResult>, _unit: Option<Unit>) -> Result<Vec<u8>> {18 let mut output = to_vec_pretty(&HyperfineSummary { results });19 for content in output.iter_mut() {20 content.push(b'\n');21 }4 unmodified linesmodified:src/hyperfine/export/markdown.rs+92 added-8 removed
1 use super::Exporter;2 3-use hyperfine::format::{Unit, format_duration_value};4-use hyperfine::types::BenchmarkResult;3+use hyperfine::format::format_duration_value;4+use hyperfine::types::{BenchmarkResult, Unit};5 6 use std::io::Result;7 8 #[derive(Default)]9 pub struct MarkdownExporter {}10 11 impl Exporter for MarkdownExporter {12- fn serialize(&self, results: &Vec<BenchmarkResult>) -> Result<Vec<u8>> {13- let unit = if let Some(first_result) = results.first() {12+ fn serialize(&self, results: &Vec<BenchmarkResult>, unit: Option<Unit>) -> Result<Vec<u8>> {13+ let unit = if unit.is_some() {14+ // Use the given unit for all entries.15+ unit.unwrap()16+ } else if let Some(first_result) = results.first() {17 // Use the first BenchmarkResult entry to determine the unit for all entries.18 format_duration_value(first_result.mean, None).119 } else {20 // Default to `Second`.40 unmodified lines61 /// benchmark results as a table. The list of actual times is not included62 /// in the output.63 ///64 /// This also demonstrates that the first entry's units (ms) are used to set62-/// the units for all entries.65+/// the units for all entries when the time unit is not given.66 #[test]67 fn test_markdown_format_ms() {68 let exporter = MarkdownExporter::default();69 20 unmodified lines90 2.0080, // max91 vec![2.0, 2.0, 2.0], // times92 ));93 91- let formatted = String::from_utf8(exporter.serialize(&timing_results).unwrap()).unwrap();94+ let formatted = String::from_utf8(exporter.serialize(&timing_results, None).unwrap()).unwrap();95 96 let formatted_expected = format!(97 "{}\98 | `sleep 0.1` | 105.7 ± 1.6 | 102.3…108.0 |3 unmodified lines102 assert_eq!(formatted_expected, formatted);103 }104 105 /// This (again) demonstrates that the first entry's units (s) are used to set103-/// the units for all entries.106+/// the units for all entries when the time unit is not given.107 #[test]108 fn test_markdown_format_s() {109 let exporter = MarkdownExporter::default();110 20 unmodified lines131 0.1080, // max132 vec![0.1, 0.1, 0.1], // times133 ));134 132- let formatted = String::from_utf8(exporter.serialize(&timing_results).unwrap()).unwrap();135+ let formatted = String::from_utf8(exporter.serialize(&timing_results, None).unwrap()).unwrap();136 137 let formatted_expected = format!(138 "{}\139 | `sleep 2` | 2.005 ± 0.002 | 2.002…2.008 |1 unmodified line141 ", table_header("s".to_string()));142 143 assert_eq!(formatted_expected, formatted);144 }145+146+/// The given time unit (s) is used to set the units for all entries.147+#[test]148+fn test_markdown_format_time_unit_s() {149+ let exporter = MarkdownExporter::default();150+151+ let mut timing_results = vec![];152+153+ timing_results.push(BenchmarkResult::new(154+ String::from("sleep 0.1"),155+ 0.1057, // mean156+ 0.0016, // std dev157+ 0.0009, // user_mean158+ 0.0011, // system_mean159+ 0.1023, // min160+ 0.1080, // max161+ vec![0.1, 0.1, 0.1], // times162+ ));163+164+ timing_results.push(BenchmarkResult::new(165+ String::from("sleep 2"),166+ 2.0050, // mean167+ 0.0020, // std dev168+ 0.0009, // user_mean169+ 0.0012, // system_mean170+ 2.0020, // min171+ 2.0080, // max172+ vec![2.0, 2.0, 2.0], // times173+ ));174+175+ let formatted = String::from_utf8(exporter.serialize(&timing_results, Some(Unit::Second)).unwrap()).unwrap();176+177+ let formatted_expected = format!(178+"{}\179+| `sleep 0.1` | 0.106 ± 0.002 | 0.102…0.108 |180+| `sleep 2` | 2.005 ± 0.002 | 2.002…2.008 |181+", table_header("s".to_string()));182+183+ assert_eq!(formatted_expected, formatted);184+}185+186+/// This (again) demonstrates that the given time unit (ms) is used to set187+/// the units for all entries.188+#[test]189+fn test_markdown_format_time_unit_ms() {190+ let exporter = MarkdownExporter::default();191+192+ let mut timing_results = vec![];193+194+ timing_results.push(BenchmarkResult::new(195+ String::from("sleep 2"),196+ 2.0050, // mean197+ 0.0020, // std dev198+ 0.0009, // user_mean199+ 0.0012, // system_mean200+ 2.0020, // min201+ 2.0080, // max202+ vec![2.0, 2.0, 2.0], // times203+ ));204+205+ timing_results.push(BenchmarkResult::new(206+ String::from("sleep 0.1"),207+ 0.1057, // mean208+ 0.0016, // std dev209+ 0.0009, // user_mean210+ 0.0011, // system_mean211+ 0.1023, // min212+ 0.1080, // max213+ vec![0.1, 0.1, 0.1], // times214+ ));215+216+ let formatted = String::from_utf8(exporter.serialize(&timing_results, Some(Unit::MilliSecond)).unwrap()).unwrap();217+218+ let formatted_expected = format!(219+"{}\220+| `sleep 2` | 2005.0 ± 2.0 | 2002.0…2008.0 |221+| `sleep 0.1` | 105.7 ± 1.6 | 102.3…108.0 |222+", table_header("ms".to_string()));223+224+ assert_eq!(formatted_expected, formatted);225+}modified:src/hyperfine/export/mod.rs+4 added-4 removed
7 unmodified lines8 9 use std::fs::File;10 use std::io::{Result, Write};11 12-use hyperfine::types::BenchmarkResult;12+use hyperfine::types::{BenchmarkResult, Unit};13 14 /// The desired form of exporter to use for a given file.15 #[derive(Clone)]16 pub enum ExportType {9 unmodified lines26 27 /// Interface for different exporters.28 trait Exporter {29 /// Export the given entries in the serialized form.30- fn serialize(&self, results: &Vec<BenchmarkResult>) -> Result<Vec<u8>>;30+ fn serialize(&self, results: &Vec<BenchmarkResult>, unit: Option<Unit>) -> Result<Vec<u8>>;31 }32 33 struct ExporterWithFilename {34 exporter: Box<Exporter>,26 unmodified lines61 });62 }63 64 /// Write the given results to all Exporters contained within this manager65- pub fn write_results(&self, results: Vec<BenchmarkResult>) -> Result<()> {65+ pub fn write_results(&self, results: Vec<BenchmarkResult>, unit: Option<Unit>) -> Result<()> {66 for e in &self.exporters {67- let file_content = e.exporter.serialize(&results)?;67+ let file_content = e.exporter.serialize(&results, unit)?;68 write_to_file(&e.filename, &file_content)?;69 }70 Ok(())71 }7 unmodified linesmodified:src/hyperfine/app.rs+14 added-4 removed
84 unmodified lines85 .arg(86 Arg::with_name("parameter-scan")87 .long("parameter-scan")88 .short("P")89+ .takes_value(true)90+ .allow_hyphen_values(true)91+ .value_names(&["VAR", "MIN", "MAX"])92 .help(93 "Perform benchmark runs for each value in the range MIN..MAX. Replaces the \94 string '{VAR}' in each command by the current parameter value.",92- )93- .takes_value(true)94- .allow_hyphen_values(true)95- .value_names(&["VAR", "MIN", "MAX"]),95+ ),96 )97 .arg(98 Arg::with_name("style")99 .long("style")24 unmodified lines124 .short("i")125 .help("Ignore non-zero exit codes."),126 )127 .arg(128+ Arg::with_name("time-unit")129+ .long("time-unit")130+ .short("u")131+ .takes_value(true)132+ .value_name("millisecond|second")133+ .possible_values(&["millisecond", "second"])134+ .help( "Set the time unit used for CLI output and Markdown export.",135+ ),136+ )137+ .arg(138 Arg::with_name("export-csv")139 .long("export-csv")140 .takes_value(true)141 .value_name("FILE")30 unmodified linesmodified:src/hyperfine/benchmark.rs+2 added-2 removed
252 unmodified lines253 for _ in 0..count_remaining {254 run_preparation_command(&options.shell, &prepare_cmd, options.show_output)?;255 256 let msg = {257- let mean = format_duration(mean(×_real), None);257+ let mean = format_duration(mean(×_real), options.time_unit);258 format!("Current estimate: {}", mean.to_string().green())259 };260 progress_bar.set_message(&msg);261 24 unmodified lines286 let user_mean = mean(×_user);287 let system_mean = mean(×_system);288 289 // Formatting and console output290- let (mean_str, unit_mean) = format_duration_unit(t_mean, None);290+ let (mean_str, unit_mean) = format_duration_unit(t_mean, options.time_unit);291 let stddev_str = format_duration(t_stddev, Some(unit_mean));292 let min_str = format_duration(t_min, Some(unit_mean));293 let max_str = format_duration(t_max, Some(unit_mean));294 63 unmodified linesmodified:src/hyperfine/format.rs+1 added-39 removed
1-use hyperfine::types::Second;1+use hyperfine::types::{Second, Unit};2 3-#[derive(Debug, Clone, Copy, PartialEq)]4-pub enum Unit {5- Second,6- MilliSecond,7-}8-9-impl Unit {10- /// The abbreviation of the Unit.11- pub fn short_name(&self) -> String {12- match *self {13- Unit::Second => String::from("s"),14- Unit::MilliSecond => String::from("ms"),15- }16- }17-18- /// Returns the Second value formatted for the Unit.19- pub fn format(&self, value: Second) -> String {20- match *self {21- Unit::Second => format!("{:.3}", value),22- Unit::MilliSecond => format!("{:.1}", value * 1e3),23- }24- }25-}26-3 /// Format the given duration as a string. The output-unit can be enforced by setting `unit` to4 /// `Some(target_unit)`. If `unit` is `None`, it will be determined automatically.5 pub fn format_duration(duration: Second, unit: Option<Unit>) -> String {6 match format_duration_unit(duration, unit) {17 unmodified lines24 }25 }26 27 #[test]52-fn test_unit_short_name() {53- assert_eq!("s", Unit::Second.short_name());54- assert_eq!("ms", Unit::MilliSecond.short_name());55-}56-57-// Note - the values are rounded when formatted.58-#[test]59-fn test_unit_format() {60- let value: Second = 123.456789;61- assert_eq!("123.457", Unit::Second.format(value));62- assert_eq!("123456.8", Unit::MilliSecond.format(value));63-}64-65-#[test]28 fn test_format_duration_unit_basic() {29 let (out_str, out_unit) = format_duration_unit(1.3, None);30 31 assert_eq!("1.300 s", out_str);35 unmodified linesmodified:src/hyperfine/types.rs+43 added
8 unmodified lines9 10 /// Type alias for unit of time11 pub type Second = f64;12 13+/// Supported time units14+#[derive(Debug, Clone, Copy, PartialEq)]15+pub enum Unit {16+ Second,17+ MilliSecond,18+}19+20+impl Unit {21+ /// The abbreviation of the Unit.22+ pub fn short_name(&self) -> String {23+ match *self {24+ Unit::Second => String::from("s"),25+ Unit::MilliSecond => String::from("ms"),26+ }27+ }28+29+ /// Returns the Second value formatted for the Unit.30+ pub fn format(&self, value: Second) -> String {31+ match *self {32+ Unit::Second => format!("{:.3}", value),33+ Unit::MilliSecond => format!("{:.1}", value * 1e3),34+ }35+ }36+}37+38 /// A command that should be benchmarked.39 #[derive(Debug, Clone)]40 pub struct Command<'a> {41 /// The command that should be executed (without parameter substitution)104 unmodified lines146 pub shell: String,147 148 /// Forward benchmark's stdout to hyperfine's stdout149 pub show_output: bool,150+151+ /// Which time unit to use for CLI & Markdown output152+ pub time_unit: Option<Unit>,153 }154 155 impl Default for HyperfineOptions {156 fn default() -> HyperfineOptions {5 unmodified lines162 preparation_command: None,163 output_style: OutputStyleOption::Full,164 shell: DEFAULT_SHELL.to_string(),165 show_output: false,166+ time_unit: None,167 }168 }169 }170 49 unmodified lines220 times: Some(times),221 }222 }223 }224+225+#[test]226+fn test_unit_short_name() {227+ assert_eq!("s", Unit::Second.short_name());228+ assert_eq!("ms", Unit::MilliSecond.short_name());229+}230+231+// Note - the values are rounded when formatted.232+#[test]233+fn test_unit_format() {234+ let value: Second = 123.456789;235+ assert_eq!("123.457", Unit::Second.format(value));236+ assert_eq!("123456.8", Unit::MilliSecond.format(value));237+}modified:src/main.rs+11 added-5 removed
44 unmodified lines45 use hyperfine::error::{OptionsError, ParameterScanError};46 use hyperfine::export::{ExportManager, ExportType};47 use hyperfine::internal::write_benchmark_comparison;48 use hyperfine::types::{49- BenchmarkResult, CmdFailureAction, Command, HyperfineOptions, OutputStyleOption,49+ BenchmarkResult, Unit, CmdFailureAction, Command, HyperfineOptions, OutputStyleOption,50 };51 52 /// Print error message to stderr and terminate53 pub fn error(message: &str) -> ! {40 unmodified lines94 let options = build_hyperfine_options(&matches);95 let export_manager = build_export_manager(&matches);96 let commands = build_commands(&matches);97 98- let res = match options {99- Ok(opts) => run(&commands, &opts),100- Err(e) => error(e.description()),98+ let res = match &options {99+ &Ok(ref opts) => run(&commands, &opts),100+ &Err(ref e) => error(e.description()),101 };102 103 match res {104 Ok(timing_results) => {105 write_benchmark_comparison(&timing_results);106- let ans = export_manager.write_results(timing_results);106+ let ans = export_manager.write_results(timing_results, options.unwrap().time_unit);107 if let Err(e) = ans {108 error(&format!(109 "The following error occurred while exporting: {}",110 e.description()84 unmodified lines195 if matches.is_present("ignore-failure") {196 options.failure_action = CmdFailureAction::Ignore;197 }198 199+ options.time_unit = match matches.value_of("time-unit") {200+ Some("millisecond") => Some(Unit::MilliSecond),201+ Some("second") => Some(Unit::Second),202+ _ => None,203+ };204+205 Ok(options)206 }207 208 /// Build the ExportManager that will export the results specified38 unmodified lines