Skip to content
Myr

Refactor code into separate modules

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by sharkdp · committed by sharkdp · parent 460fa62 · Browse files · 5 files+285 added−269 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

5 files+285 added−269 removed

  • other:+285 added−269 removed

5 files+285 added−269 removed

added:src/hyperfine/benchmark.rs+197 added
1use std::io;2use std::process::{Command, Stdio};3use std::time::Instant;45use ansi_term::Colour::{Cyan, Green, White, Yellow};67use hyperfine::internal::{get_progress_bar, HyperfineOptions, Second, Warnings, MIN_EXECUTION_TIME};8use hyperfine::statistics::mean;910/// Results from timing a single shell command11pub struct TimingResult {12 /// Execution time in seconds13 pub execution_time_sec: Second,1415 /// True if the command finished with exit code zero16 pub success: bool,17}1819impl TimingResult {20 fn new(execution_time_sec: Second, success: bool) -> TimingResult {21 TimingResult {22 execution_time_sec,23 success,24 }25 }26}2728/// Run the given shell command and measure the execution time29pub fn time_shell_command(shell_cmd: &str, ignore_failure: bool) -> io::Result<TimingResult> {30 let start = Instant::now();3132 let status = Command::new("sh")33 .arg("-c")34 .arg(shell_cmd)35 .stdin(Stdio::null())36 .stdout(Stdio::null())37 .stderr(Stdio::null())38 .status()?;3940 if !ignore_failure && !status.success() {41 return Err(io::Error::new(42 io::ErrorKind::Other,43 "Command terminated with non-zero exit code. \44 Use the '-i'/'--ignore-failure' option if you want to ignore this.",45 ));46 }4748 let duration = start.elapsed();4950 let execution_time_sec = duration.as_secs() as f64 + duration.subsec_nanos() as f64 * 1e-9;5152 Ok(TimingResult::new(execution_time_sec, status.success()))53}5455/// Measure the average shell spawning time56pub fn mean_shell_spawning_time() -> io::Result<Second> {57 const COUNT: u64 = 200;58 let bar = get_progress_bar(COUNT, "Measuring shell spawning time");5960 let mut times: Vec<Second> = vec![];61 for _ in 0..COUNT {62 let res = time_shell_command("", false);6364 match res {65 Err(_) => {66 return Err(io::Error::new(67 io::ErrorKind::Other,68 "Could not measure shell execution time. \69 Make sure you can run 'sh -c \"\"'.",70 ))71 }72 Ok(r) => {73 times.push(r.execution_time_sec);74 }75 }76 bar.inc(1);77 }78 bar.finish_and_clear();7980 let mean: f64 = mean(times.iter().cloned()); // TODO: get rid of .cloned()81 Ok(mean)82}8384/// Run the benchmark for a single shell command85pub fn run_benchmark(86 num: usize,87 cmd: &str,88 shell_spawning_time: Second,89 options: &HyperfineOptions,90) -> io::Result<()> {91 // Helper function to compute corrected execution times92 let get_execution_time = |r: &TimingResult| -> Second {93 if r.execution_time_sec < shell_spawning_time {94 0.095 } else {96 r.execution_time_sec - shell_spawning_time97 }98 };99100 println!(101 "{}{}: {}",102 White.bold().paint("Benchmark #"),103 White.bold().paint((num + 1).to_string()),104 Cyan.paint(cmd)105 );106 println!();107108 let mut results = vec![];109110 // Warmup phase111 if options.warmup_count > 0 {112 let bar = get_progress_bar(options.warmup_count, "Performing warmup runs");113114 for _ in 0..options.warmup_count {115 let _ = time_shell_command(cmd, options.ignore_failure)?;116 bar.inc(1);117 }118 bar.finish_and_clear();119 }120121 // Set up progress bar (and spinner for initial measurement)122 let bar = get_progress_bar(options.min_runs, "Initial time measurement");123124 // Initial timing run125 let res = time_shell_command(cmd, options.ignore_failure)?;126127 // Determine number of benchmark runs128 let runs_in_min_time = (options.min_time_sec / res.execution_time_sec) as u64;129130 let count = if runs_in_min_time >= options.min_runs {131 runs_in_min_time132 } else {133 options.min_runs134 };135136 let count_remaining = count - 1;137138 // Save the first result139 results.push(res);140141 // Re-configure the progress bar142 bar.set_length(count_remaining);143144 // Gather statistics145 for _ in 0..count_remaining {146 let msg = {147 let execution_times = results.iter().map(&get_execution_time);148 let mean = format!("{:.3} s", mean(execution_times));149 format!("Current estimate: {:.3}", Green.paint(mean))150 };151 bar.set_message(&msg);152153 let res = time_shell_command(cmd, options.ignore_failure)?;154 results.push(res);155 bar.inc(1);156 }157 bar.finish_and_clear();158159 // Compute statistical quantities160161 // Corrected execution times162 let execution_times = results.iter().map(&get_execution_time);163164 let t_mean = mean(execution_times.clone());165 let t2_mean = mean(execution_times.clone().map(|t| t.powi(2)));166167 let stddev = (t2_mean - t_mean.powi(2)).sqrt();168169 // Formatting and console output170 let time_fmt = format!("{:.3} s ± {:.3} s", t_mean, stddev);171172 println!(" Time: {}", Green.paint(time_fmt));173174 // Warnings175 let mut warnings = vec![];176177 // Check execution time178 if execution_times.clone().any(|t| t < MIN_EXECUTION_TIME) {179 warnings.push(Warnings::FastExecutionTime);180 }181182 // Check programm exit codes183 if results.iter().any(|r| !r.success) {184 warnings.push(Warnings::NonZeroExitCode);185 }186187 if warnings.len() > 0 {188 eprintln!();189 for warning in &warnings {190 eprintln!(" {}: {}", Yellow.paint("Warning"), warning);191 }192 }193194 println!();195196 Ok(())197}
added:src/hyperfine/internal.rs+68 added
1use std::fmt;23use indicatif::{ProgressBar, ProgressStyle};45/// Type alias for unit of time6pub type Second = f64;78/// Threshold for warning about fast execution time9pub const MIN_EXECUTION_TIME: Second = 5e-3;1011/// A set of options for hyperfine12pub struct HyperfineOptions {13 /// Number of warmup runs14 pub warmup_count: u64,1516 /// Minimum number of benchmark runs17 pub min_runs: u64,1819 /// Minimum benchmarking time20 pub min_time_sec: Second,2122 /// Whether or not to ignore non-zero exit codes23 pub ignore_failure: bool,24}2526impl Default for HyperfineOptions {27 fn default() -> HyperfineOptions {28 HyperfineOptions {29 warmup_count: 0,30 min_runs: 10,31 min_time_sec: 3.0,32 ignore_failure: false,33 }34 }35}3637/// Return a pre-configured progress bar38pub fn get_progress_bar(length: u64, msg: &str) -> ProgressBar {39 let progressbar_style = ProgressStyle::default_spinner()40 .tick_chars("⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏")41 .template(" {spinner} {msg:<30} {wide_bar} ETA {eta_precise}");4243 let bar = ProgressBar::new(length);44 bar.set_style(progressbar_style.clone());45 bar.enable_steady_tick(80);46 bar.set_message(msg);4748 bar49}5051/// Possible benchmark warnings52pub enum Warnings {53 FastExecutionTime,54 NonZeroExitCode,55}5657impl fmt::Display for Warnings {58 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {59 match self {60 &Warnings::FastExecutionTime => write!(61 f,62 "Command took less than {:.0} ms to complete. Results might be inaccurate.",63 MIN_EXECUTION_TIME * 1e364 ),65 &Warnings::NonZeroExitCode => write!(f, "Ignoring non-zero exit code."),66 }67 }68}
added:src/hyperfine/mod.rs+3 added
1pub mod benchmark;2pub mod internal;3pub mod statistics;
added:src/hyperfine/statistics.rs+13 added
1/// Calculate statistical average2pub fn mean<I>(values: I) -> f643where4 I: IntoIterator<Item = f64>,5{6 let mut sum: f64 = 0.0;7 let mut len: u64 = 0;8 for v in values {9 sum += v;10 len += 1;11 }12 sum / (len as f64)13}
modified:src/main.rs+4 added-269 removed
4 unmodified lines
56use std::cmp;7use std::error::Error;8use std::io;9use std::process::{Command, Stdio};10use std::time::Instant;11use std::fmt;913use indicatif::{ProgressBar, ProgressStyle};14use ansi_term::Colour::{Cyan, Green, Red, White, Yellow};10use ansi_term::Colour::Red;11use clap::{App, AppSettings, Arg};1217/// Type alias for unit of time18type Second = f64;13mod hyperfine;1420/// Threshold for warning about fast execution time21const MIN_EXECUTION_TIME: Second = 5e-3;15use hyperfine::internal::HyperfineOptions;16use hyperfine::benchmark::{mean_shell_spawning_time, run_benchmark};1718/// Print error message to stderr and terminate19pub fn error(message: &str) -> ! {20 eprintln!("{}: {}", Red.paint("Error"), message);21 std::process::exit(1);22}2329struct CmdResult {30 /// Execution time in seconds31 execution_time_sec: Second,3233 /// True if the command finished with exit code zero34 success: bool,35}3637impl CmdResult {38 fn new(execution_time_sec: Second, success: bool) -> CmdResult {39 CmdResult {40 execution_time_sec,41 success,42 }43 }44}4546/// Run the given shell command and measure the execution time47fn time_shell_command(shell_cmd: &str, ignore_failure: bool) -> io::Result<CmdResult> {48 let start = Instant::now();4950 let status = Command::new("sh")51 .arg("-c")52 .arg(shell_cmd)53 .stdin(Stdio::null())54 .stdout(Stdio::null())55 .stderr(Stdio::null())56 .status()?;5758 if !ignore_failure && !status.success() {59 return Err(io::Error::new(60 io::ErrorKind::Other,61 "Command terminated with non-zero exit code. \62 Use the '-i'/'--ignore-failure' option if you want to ignore this.",63 ));64 }6566 let duration = start.elapsed();6768 let execution_time_sec = duration.as_secs() as f64 + duration.subsec_nanos() as f64 * 1e-9;6970 Ok(CmdResult::new(execution_time_sec, status.success()))71}7273/// Return a pre-configured progress bar74fn get_progress_bar(length: u64, msg: &str) -> ProgressBar {75 let progressbar_style = ProgressStyle::default_spinner()76 .tick_chars("⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏")77 .template(" {spinner} {msg:<30} {wide_bar} ETA {eta_precise}");7879 let bar = ProgressBar::new(length);80 bar.set_style(progressbar_style.clone());81 bar.enable_steady_tick(80);82 bar.set_message(msg);8384 bar85}8687/// Possible benchmark warnings88enum Warnings {89 FastExecutionTime,90 NonZeroExitCode,91}9293impl fmt::Display for Warnings {94 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {95 match self {96 &Warnings::FastExecutionTime => write!(97 f,98 "Command took less than {:.0} ms to complete. Results might be inaccurate.",99 MIN_EXECUTION_TIME * 1e3100 ),101 &Warnings::NonZeroExitCode => write!(f, "Ignoring non-zero exit code."),102 }103 }104}105106/// Calculate statistical average107fn mean<I>(values: I) -> f64108where109 I: IntoIterator<Item = f64>,110{111 let mut sum: f64 = 0.0;112 let mut len: u64 = 0;113 for v in values {114 sum += v;115 len += 1;116 }117 sum / (len as f64)118}119120/// Run the benchmark for a single shell command121fn run_benchmark(122 num: usize,123 cmd: &str,124 shell_spawning_time: Second,125 options: &HyperfineOptions,126) -> io::Result<()> {127 // Helper function to compute corrected execution times128 let get_execution_time = |r: &CmdResult| -> Second {129 if r.execution_time_sec < shell_spawning_time {130 0.0131 } else {132 r.execution_time_sec - shell_spawning_time133 }134 };135136 println!(137 "{}{}: {}",138 White.bold().paint("Benchmark #"),139 White.bold().paint((num + 1).to_string()),140 Cyan.paint(cmd)141 );142 println!();143144 let mut results = vec![];145146 // Warmup phase147 if options.warmup_count > 0 {148 let bar = get_progress_bar(options.warmup_count, "Performing warmup runs");149150 for _ in 0..options.warmup_count {151 let _ = time_shell_command(cmd, options.ignore_failure)?;152 bar.inc(1);153 }154 bar.finish_and_clear();155 }156157 // Set up progress bar (and spinner for initial measurement)158 let bar = get_progress_bar(options.min_runs, "Initial time measurement");159160 // Initial timing run161 let res = time_shell_command(cmd, options.ignore_failure)?;162163 // Determine number of benchmark runs164 let runs_in_min_time = (options.min_time_sec / res.execution_time_sec) as u64;165166 let count = if runs_in_min_time >= options.min_runs {167 runs_in_min_time168 } else {169 options.min_runs170 };171172 let count_remaining = count - 1;173174 // Save the first result175 results.push(res);176177 // Re-configure the progress bar178 bar.set_length(count_remaining);179180 // Gather statistics181 for _ in 0..count_remaining {182 let msg = {183 let execution_times = results.iter().map(&get_execution_time);184 let mean = format!("{:.3} s", mean(execution_times));185 format!("Current estimate: {:.3}", Green.paint(mean))186 };187 bar.set_message(&msg);188189 let res = time_shell_command(cmd, options.ignore_failure)?;190 results.push(res);191 bar.inc(1);192 }193 bar.finish_and_clear();194195 // Compute statistical quantities196197 // Corrected execution times198 let execution_times = results.iter().map(&get_execution_time);199200 let t_mean = mean(execution_times.clone());201 let t2_mean = mean(execution_times.clone().map(|t| t.powi(2)));202203 let stddev = (t2_mean - t_mean.powi(2)).sqrt();204205 // Formatting and console output206 let time_fmt = format!("{:.3} s ± {:.3} s", t_mean, stddev);207208 println!(" Time: {}", Green.paint(time_fmt));209210 // Warnings211 let mut warnings = vec![];212213 // Check execution time214 if execution_times.clone().any(|t| t < MIN_EXECUTION_TIME) {215 warnings.push(Warnings::FastExecutionTime);216 }217218 // Check programm exit codes219 if results.iter().any(|r| !r.success) {220 warnings.push(Warnings::NonZeroExitCode);221 }222223 if warnings.len() > 0 {224 eprintln!();225 for warning in &warnings {226 eprintln!(" {}: {}", Yellow.paint("Warning"), warning);227 }228 }229230 println!();231232 Ok(())233}234235// Measure the average shell spawning time236fn mean_shell_spawning_time() -> io::Result<Second> {237 const COUNT: u64 = 200;238 let bar = get_progress_bar(COUNT, "Measuring shell spawning time");239240 let mut times: Vec<Second> = vec![];241 for _ in 0..COUNT {242 let res = time_shell_command("", false);243244 match res {245 Err(_) => {246 return Err(io::Error::new(247 io::ErrorKind::Other,248 "Could not measure shell execution time. \249 Make sure you can run 'sh -c \"\"'.",250 ))251 }252 Ok(r) => {253 times.push(r.execution_time_sec);254 }255 }256 bar.inc(1);257 }258 bar.finish_and_clear();259260 let mean: f64 = mean(times.iter().cloned()); // TODO: get rid of .cloned()261 Ok(mean)262}26324/// Runs the benchmark for the given commands25fn run(commands: &Vec<&str>, options: &HyperfineOptions) -> io::Result<()> {26 let shell_spawning_time = mean_shell_spawning_time()?;27
4 unmodified lines
3233 Ok(())34}35276pub struct HyperfineOptions {277 /// Number of warmup runs278 pub warmup_count: u64,279280 /// Minimum number of benchmark runs281 pub min_runs: u64,282283 /// Minimum benchmarking time284 pub min_time_sec: Second,285286 /// Whether or not to ignore non-zero exit codes287 pub ignore_failure: bool,288}289290impl Default for HyperfineOptions {291 fn default() -> HyperfineOptions {292 HyperfineOptions {293 warmup_count: 0,294 min_runs: 10,295 min_time_sec: 3.0,296 ignore_failure: false,297 }298 }299}30036fn main() {37 let matches = App::new("hyperfine")38 .version(crate_version!())39 .setting(AppSettings::ColoredHelp)
57 unmodified lines