Add comparison output when 2 or more commands are run
Before adoption: this commit came in with the history the project adopted, so no landing records it.
This also includes a restructure to the internal types used
authored by Steve Pentland · committed by David Peter · parent 8295327 · Browse files · 15 files·+207 added−150 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
15 files+207 added−150 removed
- other:+207 added−150 removed
Provenance
- Commit
3966bf0- Tree
e5ffb86- Author
Steve Pentland <stevepentland@gmail.com>- Committer
David Peter <sharkdp@users.noreply.github.com>- Parent
8295327
15 files changed+207 added−150 removed
modified:src/hyperfine/export/csv.rs+4 added-2 removed
1-use super::{ExportEntry, Exporter};1+use super::Exporter;2 3+use hyperfine::types::BenchmarkResult;4+5 use std::io::{Error, ErrorKind, Result};6 7 use csv::WriterBuilder;8 9 #[derive(Default)]10 pub struct CsvExporter {}11 12 impl Exporter for CsvExporter {11- fn serialize(&self, results: &Vec<ExportEntry>) -> Result<Vec<u8>> {13+ fn serialize(&self, results: &Vec<BenchmarkResult>) -> 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:17 let mut result = res.clone();10 unmodified linesmodified:src/hyperfine/export/json.rs+4 added-3 removed
1-use super::{ExportEntry, Exporter};1+use super::Exporter;2+use hyperfine::types::BenchmarkResult;3 4 use std::io::{Error, ErrorKind, Result};5 6 use serde_json::to_vec_pretty;7 8 #[derive(Serialize, Debug)]9 struct HyperfineSummary<'a> {9- results: &'a Vec<ExportEntry>,10+ results: &'a Vec<BenchmarkResult>,11 }12 13 #[derive(Default)]14 pub struct JsonExporter {}15 16 impl Exporter for JsonExporter {16- fn serialize(&self, results: &Vec<ExportEntry>) -> Result<Vec<u8>> {17+ fn serialize(&self, results: &Vec<BenchmarkResult>) -> 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+4 added-3 removed
1-use super::{ExportEntry, Exporter};1+use super::Exporter;2+use hyperfine::types::BenchmarkResult;3 4 use std::io::Result;5 6 const MULTIPLIER: f64 = 1e3;1 unmodified line8 #[derive(Default)]9 pub struct MarkdownExporter {}10 11 impl Exporter for MarkdownExporter {11- fn serialize(&self, results: &Vec<ExportEntry>) -> Result<Vec<u8>> {12+ fn serialize(&self, results: &Vec<BenchmarkResult>) -> Result<Vec<u8>> {13 let mut destination = start_table();14 15 for result in results {16 add_table_row(&mut destination, result);7 unmodified lines24 "| Benchmark | Mean [ms] | Min. [ms] | Max. [ms] |\n|----|----|----|----|\n"25 .bytes()26 .collect()27 }27-fn add_table_row(dest: &mut Vec<u8>, entry: &ExportEntry) {28+fn add_table_row(dest: &mut Vec<u8>, entry: &BenchmarkResult) {29 dest.extend(30 format!(31 "| `{}` | {:.1} ± {:.1} | {:.1} | {:.1} |\n",32 entry.command.replace("|", "\\|"),7 unmodified linesmodified:src/hyperfine/export/mod.rs+3 added-57 removed
7 unmodified lines8 9 use std::io::{Result, Write};10 use std::fs::File;11 12-use hyperfine::internal::Second;12+use hyperfine::types::BenchmarkResult;13 14-/// Set of values that will be exported.15-#[derive(Debug, Default, Clone, Serialize)]16-pub struct ExportEntry {17- /// The command that was run18- command: String,19-20- /// The mean run time21- mean: Second,22-23- /// The standard deviation of all run times24- stddev: Second,25-26- /// Time spend in user space27- user: Second,28-29- /// Time spent in system space30- system: Second,31-32- /// Min time measured33- min: Second,34-35- /// Max time measured36- max: Second,37-38- /// All run time measurements39- #[serde(skip_serializing_if = "Option::is_none")]40- times: Option<Vec<Second>>,41-}42-43-impl ExportEntry {44- /// Create a new entry with the given values.45- pub fn new(46- command: String,47- mean: Second,48- stddev: Second,49- user: Second,50- system: Second,51- min: Second,52- max: Second,53- times: Vec<Second>,54- ) -> Self {55- ExportEntry {56- command,57- mean,58- stddev,59- user,60- system,61- min,62- max,63- times: Some(times),64- }65- }66-}67-14 /// The desired form of exporter to use for a given file.15 #[derive(Clone)]16 pub enum ExportType {17 /// CSV (comma separated values) format8 unmodified lines26 27 /// Interface for different exporters.28 trait Exporter {29 /// Export the given entries in the serialized form.84- fn serialize(&self, results: &Vec<ExportEntry>) -> Result<Vec<u8>>;30+ fn serialize(&self, results: &Vec<BenchmarkResult>) -> 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 manager119- pub fn write_results(&self, results: Vec<ExportEntry>) -> Result<()> {65+ pub fn write_results(&self, results: Vec<BenchmarkResult>) -> Result<()> {66 for e in &self.exporters {67 let file_content = e.exporter.serialize(&results)?;68 write_to_file(&e.filename, &file_content)?;69 }9 unmodified linesmodified:src/hyperfine/timer/internal.rs+1 added-1 removed
1-use hyperfine::internal::Second;1+use hyperfine::types::Second;2 3 #[derive(Debug, Copy, Clone)]4 pub struct CPUTimes {5 /// Total amount of time spent executing in user mode14 unmodified linesmodified:src/hyperfine/timer/unix_timer.rs+1 added-1 removed
1 #![cfg(not(windows))]2 3 use super::internal::{CPUInterval, CPUTimes};4 use hyperfine::timer::{TimerStart, TimerStop};5-use hyperfine::internal::Second;5+use hyperfine::types::Second;6 7 use std::mem;8 use std::process::Child;9 83 unmodified linesmodified:src/hyperfine/timer/wallclocktimer.rs+1 added-1 removed
1 use std::process::Child;2 use std::time::Instant;3 4-use hyperfine::internal::Second;4+use hyperfine::types::Second;5 use hyperfine::timer::{TimerStart, TimerStop};6 7 pub struct WallClockTimer {8 start: Instant,22 unmodified linesmodified:src/hyperfine/timer/windows_timer.rs+18 added-10 removed
1 #![cfg(windows)]2 3 use super::internal::CPUTimes;4-use hyperfine::internal::Second;4+use hyperfine::types::Second;5 use hyperfine::timer::{TimerStart, TimerStop};6 7 use winapi::um::processthreadsapi::GetProcessTimes;8 use winapi::um::winnt::HANDLE;3 unmodified lines12 use std::process::Child;13 14 const HUNDRED_NS_PER_MS: i64 = 10;15 16-pub fn get_cpu_timer(process: &Child) -> Box<TimerStop<Result=(Second,Second)>> {16+pub fn get_cpu_timer(process: &Child) -> Box<TimerStop<Result = (Second, Second)>> {17 Box::new(CPUTimer::start_for_process(process))18 }19 20 struct CPUTimer {21 handle: RawHandle,22 }23 24 impl TimerStart for CPUTimer {25-25 fn start() -> Self {26 panic!()27 }28 29 fn start_for_process(process: &Child) -> Self {31- CPUTimer { handle: process.as_raw_handle() }32- } 30+ CPUTimer {31+ handle: process.as_raw_handle(),32+ }33+ }34 }35 36 impl TimerStop for CPUTimer {37 type Result = (Second, Second);38 39 fn stop(&self) -> Self::Result {40 let times = get_cpu_times(self.handle);40- (times.user_usec as f64 * 1e-6, times.system_usec as f64 * 1e-6)41+ (42+ times.user_usec as f64 * 1e-6,43+ times.system_usec as f64 * 1e-6,44+ )45 }46 }47 48 /// Read CPU execution times (dummy for now)13 unmodified lines62 63 // GetProcessTimes will exit with non-zero if success as per: https://msdn.microsoft.com/en-us/library/windows/desktop/ms683223(v=vs.85).aspx64 if res != 0 {65 // Extract times as laid out here: https://support.microsoft.com/en-us/help/188768/info-working-with-the-filetime-structure62- // Both user_time and kernel_time are spans that the proces spent in either. 63- let user: i64 = (((user_time.dwHighDateTime as i64) << 32) + user_time.dwLowDateTime as i64) / HUNDRED_NS_PER_MS;64- let kernel: i64 = (((kernel_time.dwHighDateTime as i64) << 32) + kernel_time.dwLowDateTime as i64) / HUNDRED_NS_PER_MS;66+ // 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) / HUNDRED_NS_PER_MS;69+ let kernel: i64 = (((kernel_time.dwHighDateTime as i64) << 32)70+ + kernel_time.dwLowDateTime as i64)71+ / HUNDRED_NS_PER_MS;72 (user, kernel)73 } else {74 (0, 0)75 }76 };77 78 CPUTimes {72- user_usec, system_usec,79+ user_usec,80+ system_usec,81 }82 }modified:src/hyperfine/benchmark.rs+5 added-5 removed
1 unmodified line2 3 use colored::*;4 use statistical::{mean, standard_deviation};5 6-use hyperfine::internal::{get_progress_bar, max, min, CmdFailureAction, HyperfineOptions,7- OutputStyleOption, Second, MIN_EXECUTION_TIME};6+use hyperfine::internal::{get_progress_bar, max, min, MIN_EXECUTION_TIME};7+use hyperfine::types::{CmdFailureAction, HyperfineOptions, OutputStyleOption, Second};8 use hyperfine::warnings::Warnings;9 use hyperfine::format::{format_duration, format_duration_unit};10 use hyperfine::outlier_detection::{modified_zscores, OUTLIER_THRESHOLD};11 use hyperfine::timer::{TimerStart, TimerStop};12 use hyperfine::timer::wallclocktimer::WallClockTimer;13 use hyperfine::shell::execute_and_time;14-use hyperfine::export::ExportEntry;14+use hyperfine::types::BenchmarkResult;15 16 /// Results from timing a single shell command17 #[derive(Debug, Default, Copy, Clone)]18 pub struct TimingResult {117 unmodified lines136 num: usize,137 cmd: &str,138 shell_spawning_time: TimingResult,139 options: &HyperfineOptions,140-) -> io::Result<ExportEntry> {140+) -> io::Result<BenchmarkResult> {141 println!(142 "{}{}: {}",143 "Benchmark #".bold(),144 (num + 1).to_string().bold(),148 unmodified lines293 }294 295 println!(" ");296 297- Ok(ExportEntry::new(297+ Ok(BenchmarkResult::new(298 cmd.to_string(),299 t_mean,300 t_stddev,301 user_mean,6 unmodified linesmodified:src/hyperfine/format.rs+1 added-1 removed
1-use hyperfine::internal::Second;1+use hyperfine::types::Second;2 3 #[derive(Debug, Clone, Copy, PartialEq)]4 pub enum Unit {5 Second,60 unmodified linesmodified:src/hyperfine/internal.rs+38 added-59 removed
1+use colored::*;2 use indicatif::{ProgressBar, ProgressStyle};3 3-/// Type alias for unit of time4-pub type Second = f64;4+use hyperfine::types::{BenchmarkResult, OutputStyleOption, Second};5 6+use std::cmp::Ordering;7+use std::iter::Iterator;8+9 /// Threshold for warning about fast execution time10 pub const MIN_EXECUTION_TIME: Second = 5e-3;11 9-/// Action to take when an executed command fails.10-#[derive(Debug, Clone, Copy, PartialEq)]11-pub enum CmdFailureAction {12- /// Exit with an error message13- RaiseError,14-15- /// Simply ignore the non-zero exit code16- Ignore,17-}18-19-/// Output style type option20-#[derive(Debug, Clone, Copy, PartialEq)]21-pub enum OutputStyleOption {22- /// Do not output with colors or any special formatting23- Basic,24-25- /// Output with full color and formatting26- Full,27-28- /// Keep elements such as progress bar, but use no coloring29- NoColor,30-}31-32-/// A set of options for hyperfine33-pub struct HyperfineOptions {34- /// Number of warmup runs35- pub warmup_count: u64,36-37- /// Minimum number of benchmark runs38- pub min_runs: u64,39-40- /// Minimum benchmarking time41- pub min_time_sec: Second,42-43- /// Whether or not to ignore non-zero exit codes44- pub failure_action: CmdFailureAction,45-46- /// Command to run before each timing run47- pub preparation_command: Option<String>,48-49- /// What color mode to use for output50- pub output_style: OutputStyleOption,51-}52-53-impl Default for HyperfineOptions {54- fn default() -> HyperfineOptions {55- HyperfineOptions {56- warmup_count: 0,57- min_runs: 10,58- min_time_sec: 3.0,59- failure_action: CmdFailureAction::RaiseError,60- preparation_command: None,61- output_style: OutputStyleOption::Full,62- }63- }64-}65-12 /// Return a pre-configured progress bar13 pub fn get_progress_bar(length: u64, msg: &str, option: &OutputStyleOption) -> ProgressBar {14 let progressbar_style = match *option {15 OutputStyleOption::Basic => ProgressStyle::default_bar(),26 unmodified lines42 .min_by(|a, b| a.partial_cmp(b).unwrap())43 .unwrap()44 }45 46+pub fn write_benchmark_comparison(results: &Vec<BenchmarkResult>) {47+ if results.len() < 2 {48+ return;49+ }50+51+ // Show which was faster, maybe expand to table later?52+ let mut fastest_item: &BenchmarkResult = &results[0];53+ let mut longer_items: Vec<&BenchmarkResult> = Vec::new();54+55+ for run in &results[1..] {56+ if let Some(Ordering::Less) = fastest_item.mean.partial_cmp(&run.mean) {57+ longer_items.push(run);58+ } else {59+ longer_items.push(fastest_item);60+ fastest_item = run;61+ }62+ }63+64+ println!("{}\n", "Result Comparison".bold());65+ println!("'{}' ran", fastest_item.command.cyan());66+ longer_items.sort_by(|l, r| l.mean.partial_cmp(&r.mean).unwrap_or(Ordering::Equal));67+68+ for item in longer_items {69+ println!(70+ "{} faster than '{}'",71+ format!("{:8.2}x", item.mean / fastest_item.mean)72+ .bold()73+ .green(),74+ &item.command.magenta()75+ );76+ }77+}78+79 #[test]80 fn test_max() {81 assert_eq!(1.0, max(&[1.0]));82 assert_eq!(-1.0, max(&[-1.0]));4 unmodified linesmodified:src/hyperfine/mod.rs+4 added-3 removed
1 pub mod benchmark;2+pub mod export;3 pub mod format;4 pub mod internal;5 pub mod outlier_detection;5-pub mod warnings;6-pub mod timer;6 pub mod shell;8-pub mod export;7+pub mod timer;8+pub mod types;9+pub mod warnings;added:src/hyperfine/types.rs+116 added
1+/// The types module contains common internal types for the application.2+///3+4+/// Type alias for unit of time5+pub type Second = f64;6+7+/// Action to take when an executed command fails.8+#[derive(Debug, Clone, Copy, PartialEq)]9+pub enum CmdFailureAction {10+ /// Exit with an error message11+ RaiseError,12+13+ /// Simply ignore the non-zero exit code14+ Ignore,15+}16+17+/// Output style type option18+#[derive(Debug, Clone, Copy, PartialEq)]19+pub enum OutputStyleOption {20+ /// Do not output with colors or any special formatting21+ Basic,22+23+ /// Output with full color and formatting24+ Full,25+26+ /// Keep elements such as progress bar, but use no coloring27+ NoColor,28+}29+30+/// A set of options for hyperfine31+pub struct HyperfineOptions {32+ /// Number of warmup runs33+ pub warmup_count: u64,34+35+ /// Minimum number of benchmark runs36+ pub min_runs: u64,37+38+ /// Minimum benchmarking time39+ pub min_time_sec: Second,40+41+ /// Whether or not to ignore non-zero exit codes42+ pub failure_action: CmdFailureAction,43+44+ /// Command to run before each timing run45+ pub preparation_command: Option<String>,46+47+ /// What color mode to use for output48+ pub output_style: OutputStyleOption,49+}50+51+impl Default for HyperfineOptions {52+ fn default() -> HyperfineOptions {53+ HyperfineOptions {54+ warmup_count: 0,55+ min_runs: 10,56+ min_time_sec: 3.0,57+ failure_action: CmdFailureAction::RaiseError,58+ preparation_command: None,59+ output_style: OutputStyleOption::Full,60+ }61+ }62+}63+64+/// Set of values that will be exported.65+#[derive(Debug, Default, Clone, Serialize)]66+pub struct BenchmarkResult {67+ /// The command that was run68+ pub command: String,69+70+ /// The mean run time71+ pub mean: Second,72+73+ /// The standard deviation of all run times74+ pub stddev: Second,75+76+ /// Time spend in user space77+ pub user: Second,78+79+ /// Time spent in system space80+ pub system: Second,81+82+ /// Min time measured83+ pub min: Second,84+85+ /// Max time measured86+ pub max: Second,87+88+ /// All run time measurements89+ #[serde(skip_serializing_if = "Option::is_none")]90+ pub times: Option<Vec<Second>>,91+}92+93+impl BenchmarkResult {94+ /// Create a new entry with the given values.95+ pub fn new(96+ command: String,97+ mean: Second,98+ stddev: Second,99+ user: Second,100+ system: Second,101+ min: Second,102+ max: Second,103+ times: Vec<Second>,104+ ) -> Self {105+ BenchmarkResult {106+ command,107+ mean,108+ stddev,109+ user,110+ system,111+ min,112+ max,113+ times: Some(times),114+ }115+ }116+}modified:src/hyperfine/warnings.rs+2 added-1 removed
1 use std::fmt;2 3-use hyperfine::internal::{Second, MIN_EXECUTION_TIME};3+use hyperfine::internal::MIN_EXECUTION_TIME;4+use hyperfine::types::Second;5 use hyperfine::format::format_duration;6 7 /// A list of all possible warnings8 pub enum Warnings {33 unmodified linesmodified:src/main.rs+5 added-3 removed
35 unmodified lines36 use clap::{App, AppSettings, Arg};37 38 mod hyperfine;39 40-use hyperfine::internal::{CmdFailureAction, HyperfineOptions, OutputStyleOption};40+use hyperfine::internal::write_benchmark_comparison;41+use hyperfine::types::{BenchmarkResult, CmdFailureAction, HyperfineOptions, OutputStyleOption};42 use hyperfine::benchmark::{mean_shell_spawning_time, run_benchmark};42-use hyperfine::export::{ExportEntry, ExportManager, ExportType};43+use hyperfine::export::{ExportManager, ExportType};44 45 /// Print error message to stderr and terminate46 pub fn error(message: &str) -> ! {47 eprintln!("{} {}", "Error:".red(), message);48 std::process::exit(1);49 }50 51 /// Runs the benchmark for the given commands51-fn run(commands: &Vec<&str>, options: &HyperfineOptions) -> io::Result<Vec<ExportEntry>> {52+fn run(commands: &Vec<&str>, options: &HyperfineOptions) -> io::Result<Vec<BenchmarkResult>> {53 let shell_spawning_time = mean_shell_spawning_time(&options.output_style)?;54 55 let mut timing_results = vec![];56 160 unmodified lines217 let res = run(&commands, &options);218 219 match res {220 Ok(timing_results) => {221+ write_benchmark_comparison(&timing_results);222 let ans = export_manager.write_results(timing_results);223 if let Err(e) = ans {224 error(&format!(225 "The following error occured while exporting: {}",7 unmodified lines