Skip to content
Myr

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

9 files+172 added−67 removed

modified:src/hyperfine/export/csv.rs+3 added-3 removed
1use super::Exporter;23use hyperfine::types::BenchmarkResult;3use hyperfine::types::{BenchmarkResult, Unit};45use std::io::{Error, ErrorKind, Result};67use csv::WriterBuilder;
1 unmodified line
9#[derive(Default)]10pub struct CsvExporter {}1112impl 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;1920 writer.serialize(result)?;
7 unmodified lines
modified:src/hyperfine/export/json.rs+2 added-2 removed
1use super::Exporter;2use hyperfine::types::BenchmarkResult;2use hyperfine::types::{BenchmarkResult, Unit};34use std::io::{Error, ErrorKind, Result};56use serde_json::to_vec_pretty;
6 unmodified lines
13#[derive(Default)]14pub struct JsonExporter {}1516impl 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 lines
modified:src/hyperfine/export/markdown.rs+92 added-8 removed
1use super::Exporter;23use hyperfine::format::{Unit, format_duration_value};4use hyperfine::types::BenchmarkResult;3use hyperfine::format::format_duration_value;4use hyperfine::types::{BenchmarkResult, Unit};56use std::io::Result;78#[derive(Default)]9pub struct MarkdownExporter {}1011impl 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 lines
61/// 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]67fn test_markdown_format_ms() {68 let exporter = MarkdownExporter::default();69
20 unmodified lines
90 2.0080, // max91 vec![2.0, 2.0, 2.0], // times92 ));9391 let formatted = String::from_utf8(exporter.serialize(&timing_results).unwrap()).unwrap();94 let formatted = String::from_utf8(exporter.serialize(&timing_results, None).unwrap()).unwrap();9596 let formatted_expected = format!(97"{}\98| `sleep 0.1` | 105.7 ± 1.6 | 102.3…108.0 |
3 unmodified lines
102 assert_eq!(formatted_expected, formatted);103}104105/// 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]108fn test_markdown_format_s() {109 let exporter = MarkdownExporter::default();110
20 unmodified lines
131 0.1080, // max132 vec![0.1, 0.1, 0.1], // times133 ));134132 let formatted = String::from_utf8(exporter.serialize(&timing_results).unwrap()).unwrap();135 let formatted = String::from_utf8(exporter.serialize(&timing_results, None).unwrap()).unwrap();136137 let formatted_expected = format!(138"{}\139| `sleep 2` | 2.005 ± 0.002 | 2.002…2.008 |
1 unmodified line
141", table_header("s".to_string()));142143 assert_eq!(formatted_expected, formatted);144}145146/// The given time unit (s) is used to set the units for all entries.147#[test]148fn test_markdown_format_time_unit_s() {149 let exporter = MarkdownExporter::default();150151 let mut timing_results = vec![];152153 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 ));163164 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 ));174175 let formatted = String::from_utf8(exporter.serialize(&timing_results, Some(Unit::Second)).unwrap()).unwrap();176177 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()));182183 assert_eq!(formatted_expected, formatted);184}185186/// This (again) demonstrates that the given time unit (ms) is used to set187/// the units for all entries.188#[test]189fn test_markdown_format_time_unit_ms() {190 let exporter = MarkdownExporter::default();191192 let mut timing_results = vec![];193194 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 ));204205 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 ));215216 let formatted = String::from_utf8(exporter.serialize(&timing_results, Some(Unit::MilliSecond)).unwrap()).unwrap();217218 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()));223224 assert_eq!(formatted_expected, formatted);225}
modified:src/hyperfine/export/mod.rs+4 added-4 removed
7 unmodified lines
89use std::fs::File;10use std::io::{Result, Write};1112use hyperfine::types::BenchmarkResult;12use hyperfine::types::{BenchmarkResult, Unit};1314/// The desired form of exporter to use for a given file.15#[derive(Clone)]16pub enum ExportType {
9 unmodified lines
2627/// Interface for different exporters.28trait 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}3233struct ExporterWithFilename {34 exporter: Box<Exporter>,
26 unmodified lines
61 });62 }6364 /// 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 lines
modified:src/hyperfine/app.rs+14 added-4 removed
84 unmodified lines
85 .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 lines
124 .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 lines
modified:src/hyperfine/benchmark.rs+2 added-2 removed
252 unmodified lines
253 for _ in 0..count_remaining {254 run_preparation_command(&options.shell, &prepare_cmd, options.show_output)?;255256 let msg = {257 let mean = format_duration(mean(&times_real), None);257 let mean = format_duration(mean(&times_real), options.time_unit);258 format!("Current estimate: {}", mean.to_string().green())259 };260 progress_bar.set_message(&msg);261
24 unmodified lines
286 let user_mean = mean(&times_user);287 let system_mean = mean(&times_system);288289 // 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 lines
modified:src/hyperfine/format.rs+1 added-39 removed
1use hyperfine::types::Second;1use hyperfine::types::{Second, Unit};23#[derive(Debug, Clone, Copy, PartialEq)]4pub enum Unit {5 Second,6 MilliSecond,7}89impl 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 }1718 /// 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}263/// 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 match format_duration_unit(duration, unit) {
17 unmodified lines
24 }25}2627#[test]52fn test_unit_short_name() {53 assert_eq!("s", Unit::Second.short_name());54 assert_eq!("ms", Unit::MilliSecond.short_name());55}5657// Note - the values are rounded when formatted.58#[test]59fn 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}6465#[test]28fn test_format_duration_unit_basic() {29 let (out_str, out_unit) = format_duration_unit(1.3, None);3031 assert_eq!("1.300 s", out_str);
35 unmodified lines
modified:src/hyperfine/types.rs+43 added
8 unmodified lines
910/// Type alias for unit of time11pub type Second = f64;1213/// Supported time units14#[derive(Debug, Clone, Copy, PartialEq)]15pub enum Unit {16 Second,17 MilliSecond,18}1920impl 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 }2829 /// 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}3738/// A command that should be benchmarked.39#[derive(Debug, Clone)]40pub struct Command<'a> {41 /// The command that should be executed (without parameter substitution)
104 unmodified lines
146 pub shell: String,147148 /// Forward benchmark's stdout to hyperfine's stdout149 pub show_output: bool,150151 /// Which time unit to use for CLI & Markdown output152 pub time_unit: Option<Unit>,153}154155impl Default for HyperfineOptions {156 fn default() -> HyperfineOptions {
5 unmodified lines
162 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 lines
220 times: Some(times),221 }222 }223}224225#[test]226fn test_unit_short_name() {227 assert_eq!("s", Unit::Second.short_name());228 assert_eq!("ms", Unit::MilliSecond.short_name());229}230231// Note - the values are rounded when formatted.232#[test]233fn 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 lines
45use hyperfine::error::{OptionsError, ParameterScanError};46use hyperfine::export::{ExportManager, ExportType};47use hyperfine::internal::write_benchmark_comparison;48use hyperfine::types::{49 BenchmarkResult, CmdFailureAction, Command, HyperfineOptions, OutputStyleOption,49 BenchmarkResult, Unit, CmdFailureAction, Command, HyperfineOptions, OutputStyleOption,50};5152/// Print error message to stderr and terminate53pub fn error(message: &str) -> ! {
40 unmodified lines
94 let options = build_hyperfine_options(&matches);95 let export_manager = build_export_manager(&matches);96 let commands = build_commands(&matches);9798 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 };102103 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 lines
195 if matches.is_present("ignore-failure") {196 options.failure_action = CmdFailureAction::Ignore;197 }198199 options.time_unit = match matches.value_of("time-unit") {200 Some("millisecond") => Some(Unit::MilliSecond),201 Some("second") => Some(Unit::Second),202 _ => None,203 };204205 Ok(options)206}207208/// Build the ExportManager that will export the results specified
38 unmodified lines