Skip to content
Myr

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

15 files+207 added−150 removed

modified:src/hyperfine/export/csv.rs+4 added-2 removed
1use super::{ExportEntry, Exporter};1use super::Exporter;23use hyperfine::types::BenchmarkResult;45use std::io::{Error, ErrorKind, Result};67use csv::WriterBuilder;89#[derive(Default)]10pub struct CsvExporter {}1112impl 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 lines
modified:src/hyperfine/export/json.rs+4 added-3 removed
1use super::{ExportEntry, Exporter};1use super::Exporter;2use hyperfine::types::BenchmarkResult;34use std::io::{Error, ErrorKind, Result};56use serde_json::to_vec_pretty;78#[derive(Serialize, Debug)]9struct HyperfineSummary<'a> {9 results: &'a Vec<ExportEntry>,10 results: &'a Vec<BenchmarkResult>,11}1213#[derive(Default)]14pub struct JsonExporter {}1516impl 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 lines
modified:src/hyperfine/export/markdown.rs+4 added-3 removed
1use super::{ExportEntry, Exporter};1use super::Exporter;2use hyperfine::types::BenchmarkResult;34use std::io::Result;56const MULTIPLIER: f64 = 1e3;
1 unmodified line
8#[derive(Default)]9pub struct MarkdownExporter {}1011impl 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();1415 for result in results {16 add_table_row(&mut destination, result);
7 unmodified lines
24 "| Benchmark | Mean [ms] | Min. [ms] | Max. [ms] |\n|----|----|----|----|\n"25 .bytes()26 .collect()27}27fn add_table_row(dest: &mut Vec<u8>, entry: &ExportEntry) {28fn 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 lines
modified:src/hyperfine/export/mod.rs+3 added-57 removed
7 unmodified lines
89use std::io::{Result, Write};10use std::fs::File;1112use hyperfine::internal::Second;12use hyperfine::types::BenchmarkResult;1314/// Set of values that will be exported.15#[derive(Debug, Default, Clone, Serialize)]16pub struct ExportEntry {17 /// The command that was run18 command: String,1920 /// The mean run time21 mean: Second,2223 /// The standard deviation of all run times24 stddev: Second,2526 /// Time spend in user space27 user: Second,2829 /// Time spent in system space30 system: Second,3132 /// Min time measured33 min: Second,3435 /// Max time measured36 max: Second,3738 /// All run time measurements39 #[serde(skip_serializing_if = "Option::is_none")]40 times: Option<Vec<Second>>,41}4243impl 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}6714/// The desired form of exporter to use for a given file.15#[derive(Clone)]16pub enum ExportType {17 /// CSV (comma separated values) format
8 unmodified lines
2627/// Interface for different exporters.28trait 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}3233struct ExporterWithFilename {34 exporter: Box<Exporter>,
26 unmodified lines
61 });62 }6364 /// 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 lines
modified:src/hyperfine/timer/internal.rs+1 added-1 removed
1use hyperfine::internal::Second;1use hyperfine::types::Second;23#[derive(Debug, Copy, Clone)]4pub struct CPUTimes {5 /// Total amount of time spent executing in user mode
14 unmodified lines
modified:src/hyperfine/timer/unix_timer.rs+1 added-1 removed
1#![cfg(not(windows))]23use super::internal::{CPUInterval, CPUTimes};4use hyperfine::timer::{TimerStart, TimerStop};5use hyperfine::internal::Second;5use hyperfine::types::Second;67use std::mem;8use std::process::Child;9
83 unmodified lines
modified:src/hyperfine/timer/wallclocktimer.rs+1 added-1 removed
1use std::process::Child;2use std::time::Instant;34use hyperfine::internal::Second;4use hyperfine::types::Second;5use hyperfine::timer::{TimerStart, TimerStop};67pub struct WallClockTimer {8 start: Instant,
22 unmodified lines
modified:src/hyperfine/timer/windows_timer.rs+18 added-10 removed
1#![cfg(windows)]23use super::internal::CPUTimes;4use hyperfine::internal::Second;4use hyperfine::types::Second;5use hyperfine::timer::{TimerStart, TimerStop};67use winapi::um::processthreadsapi::GetProcessTimes;8use winapi::um::winnt::HANDLE;
3 unmodified lines
12use std::process::Child;1314const HUNDRED_NS_PER_MS: i64 = 10;1516pub fn get_cpu_timer(process: &Child) -> Box<TimerStop<Result=(Second,Second)>> {16pub fn get_cpu_timer(process: &Child) -> Box<TimerStop<Result = (Second, Second)>> {17 Box::new(CPUTimer::start_for_process(process))18}1920struct CPUTimer {21 handle: RawHandle,22}2324impl TimerStart for CPUTimer {2525 fn start() -> Self {26 panic!()27 }2829 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}3536impl TimerStop for CPUTimer {37 type Result = (Second, Second);3839 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}4748/// Read CPU execution times (dummy for now)
13 unmodified lines
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-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 };7778 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 line
23use colored::*;4use statistical::{mean, standard_deviation};56use hyperfine::internal::{get_progress_bar, max, min, CmdFailureAction, HyperfineOptions,7 OutputStyleOption, Second, MIN_EXECUTION_TIME};6use hyperfine::internal::{get_progress_bar, max, min, MIN_EXECUTION_TIME};7use hyperfine::types::{CmdFailureAction, HyperfineOptions, OutputStyleOption, Second};8use hyperfine::warnings::Warnings;9use hyperfine::format::{format_duration, format_duration_unit};10use hyperfine::outlier_detection::{modified_zscores, OUTLIER_THRESHOLD};11use hyperfine::timer::{TimerStart, TimerStop};12use hyperfine::timer::wallclocktimer::WallClockTimer;13use hyperfine::shell::execute_and_time;14use hyperfine::export::ExportEntry;14use hyperfine::types::BenchmarkResult;1516/// Results from timing a single shell command17#[derive(Debug, Default, Copy, Clone)]18pub struct TimingResult {
117 unmodified lines
136 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 lines
293 }294295 println!(" ");296297 Ok(ExportEntry::new(297 Ok(BenchmarkResult::new(298 cmd.to_string(),299 t_mean,300 t_stddev,301 user_mean,
6 unmodified lines
modified:src/hyperfine/format.rs+1 added-1 removed
1use hyperfine::internal::Second;1use hyperfine::types::Second;23#[derive(Debug, Clone, Copy, PartialEq)]4pub enum Unit {5 Second,
60 unmodified lines
modified:src/hyperfine/internal.rs+38 added-59 removed
1use colored::*;2use indicatif::{ProgressBar, ProgressStyle};33/// Type alias for unit of time4pub type Second = f64;4use hyperfine::types::{BenchmarkResult, OutputStyleOption, Second};56use std::cmp::Ordering;7use std::iter::Iterator;89/// Threshold for warning about fast execution time10pub const MIN_EXECUTION_TIME: Second = 5e-3;119/// 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,30}3132/// A set of options for hyperfine33pub struct HyperfineOptions {34 /// Number of warmup runs35 pub warmup_count: u64,3637 /// Minimum number of benchmark runs38 pub min_runs: u64,3940 /// Minimum benchmarking time41 pub min_time_sec: Second,4243 /// Whether or not to ignore non-zero exit codes44 pub failure_action: CmdFailureAction,4546 /// Command to run before each timing run47 pub preparation_command: Option<String>,4849 /// What color mode to use for output50 pub output_style: OutputStyleOption,51}5253impl 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}6512/// Return a pre-configured progress bar13pub 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 lines
42 .min_by(|a, b| a.partial_cmp(b).unwrap())43 .unwrap()44}4546pub fn write_benchmark_comparison(results: &Vec<BenchmarkResult>) {47 if results.len() < 2 {48 return;49 }5051 // 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();5455 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 }6364 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));6768 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}7879#[test]80fn test_max() {81 assert_eq!(1.0, max(&[1.0]));82 assert_eq!(-1.0, max(&[-1.0]));
4 unmodified lines
modified:src/hyperfine/mod.rs+4 added-3 removed
1pub mod benchmark;2pub mod export;3pub mod format;4pub mod internal;5pub mod outlier_detection;5pub mod warnings;6pub mod timer;6pub mod shell;8pub mod export;7pub mod timer;8pub mod types;9pub mod warnings;
added:src/hyperfine/types.rs+116 added
1/// The types module contains common internal types for the application.2///34/// Type alias for unit of time5pub type Second = f64;67/// Action to take when an executed command fails.8#[derive(Debug, Clone, Copy, PartialEq)]9pub enum CmdFailureAction {10 /// Exit with an error message11 RaiseError,1213 /// Simply ignore the non-zero exit code14 Ignore,15}1617/// Output style type option18#[derive(Debug, Clone, Copy, PartialEq)]19pub enum OutputStyleOption {20 /// Do not output with colors or any special formatting21 Basic,2223 /// Output with full color and formatting24 Full,2526 /// Keep elements such as progress bar, but use no coloring27 NoColor,28}2930/// A set of options for hyperfine31pub struct HyperfineOptions {32 /// Number of warmup runs33 pub warmup_count: u64,3435 /// Minimum number of benchmark runs36 pub min_runs: u64,3738 /// Minimum benchmarking time39 pub min_time_sec: Second,4041 /// Whether or not to ignore non-zero exit codes42 pub failure_action: CmdFailureAction,4344 /// Command to run before each timing run45 pub preparation_command: Option<String>,4647 /// What color mode to use for output48 pub output_style: OutputStyleOption,49}5051impl 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}6364/// Set of values that will be exported.65#[derive(Debug, Default, Clone, Serialize)]66pub struct BenchmarkResult {67 /// The command that was run68 pub command: String,6970 /// The mean run time71 pub mean: Second,7273 /// The standard deviation of all run times74 pub stddev: Second,7576 /// Time spend in user space77 pub user: Second,7879 /// Time spent in system space80 pub system: Second,8182 /// Min time measured83 pub min: Second,8485 /// Max time measured86 pub max: Second,8788 /// All run time measurements89 #[serde(skip_serializing_if = "Option::is_none")]90 pub times: Option<Vec<Second>>,91}9293impl 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
1use std::fmt;23use hyperfine::internal::{Second, MIN_EXECUTION_TIME};3use hyperfine::internal::MIN_EXECUTION_TIME;4use hyperfine::types::Second;5use hyperfine::format::format_duration;67/// A list of all possible warnings8pub enum Warnings {
33 unmodified lines
modified:src/main.rs+5 added-3 removed
35 unmodified lines
36use clap::{App, AppSettings, Arg};3738mod hyperfine;3940use hyperfine::internal::{CmdFailureAction, HyperfineOptions, OutputStyleOption};40use hyperfine::internal::write_benchmark_comparison;41use hyperfine::types::{BenchmarkResult, CmdFailureAction, HyperfineOptions, OutputStyleOption};42use hyperfine::benchmark::{mean_shell_spawning_time, run_benchmark};42use hyperfine::export::{ExportEntry, ExportManager, ExportType};43use hyperfine::export::{ExportManager, ExportType};4445/// Print error message to stderr and terminate46pub fn error(message: &str) -> ! {47 eprintln!("{} {}", "Error:".red(), message);48 std::process::exit(1);49}5051/// Runs the benchmark for the given commands51fn run(commands: &Vec<&str>, options: &HyperfineOptions) -> io::Result<Vec<ExportEntry>> {52fn run(commands: &Vec<&str>, options: &HyperfineOptions) -> io::Result<Vec<BenchmarkResult>> {53 let shell_spawning_time = mean_shell_spawning_time(&options.output_style)?;5455 let mut timing_results = vec![];56
160 unmodified lines
217 let res = run(&commands, &options);218219 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