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
Provenance
- Commit
2ba3160- Tree
6cd4fbf- Author
sharkdp <davidpeter@web.de>- Committer
sharkdp <davidpeter@web.de>- Parent
460fa62
5 files changed+285 added−269 removed
added:src/hyperfine/benchmark.rs+197 added
1+use std::io;2+use std::process::{Command, Stdio};3+use std::time::Instant;4+5+use ansi_term::Colour::{Cyan, Green, White, Yellow};6+7+use hyperfine::internal::{get_progress_bar, HyperfineOptions, Second, Warnings, MIN_EXECUTION_TIME};8+use hyperfine::statistics::mean;9+10+/// Results from timing a single shell command11+pub struct TimingResult {12+ /// Execution time in seconds13+ pub execution_time_sec: Second,14+15+ /// True if the command finished with exit code zero16+ pub success: bool,17+}18+19+impl TimingResult {20+ fn new(execution_time_sec: Second, success: bool) -> TimingResult {21+ TimingResult {22+ execution_time_sec,23+ success,24+ }25+ }26+}27+28+/// Run the given shell command and measure the execution time29+pub fn time_shell_command(shell_cmd: &str, ignore_failure: bool) -> io::Result<TimingResult> {30+ let start = Instant::now();31+32+ 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()?;39+40+ 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+ }47+48+ let duration = start.elapsed();49+50+ let execution_time_sec = duration.as_secs() as f64 + duration.subsec_nanos() as f64 * 1e-9;51+52+ Ok(TimingResult::new(execution_time_sec, status.success()))53+}54+55+/// Measure the average shell spawning time56+pub fn mean_shell_spawning_time() -> io::Result<Second> {57+ const COUNT: u64 = 200;58+ let bar = get_progress_bar(COUNT, "Measuring shell spawning time");59+60+ let mut times: Vec<Second> = vec![];61+ for _ in 0..COUNT {62+ let res = time_shell_command("", false);63+64+ 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();79+80+ let mean: f64 = mean(times.iter().cloned()); // TODO: get rid of .cloned()81+ Ok(mean)82+}83+84+/// Run the benchmark for a single shell command85+pub 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+ };99+100+ println!(101+ "{}{}: {}",102+ White.bold().paint("Benchmark #"),103+ White.bold().paint((num + 1).to_string()),104+ Cyan.paint(cmd)105+ );106+ println!();107+108+ let mut results = vec![];109+110+ // Warmup phase111+ if options.warmup_count > 0 {112+ let bar = get_progress_bar(options.warmup_count, "Performing warmup runs");113+114+ 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+ }120+121+ // Set up progress bar (and spinner for initial measurement)122+ let bar = get_progress_bar(options.min_runs, "Initial time measurement");123+124+ // Initial timing run125+ let res = time_shell_command(cmd, options.ignore_failure)?;126+127+ // Determine number of benchmark runs128+ let runs_in_min_time = (options.min_time_sec / res.execution_time_sec) as u64;129+130+ let count = if runs_in_min_time >= options.min_runs {131+ runs_in_min_time132+ } else {133+ options.min_runs134+ };135+136+ let count_remaining = count - 1;137+138+ // Save the first result139+ results.push(res);140+141+ // Re-configure the progress bar142+ bar.set_length(count_remaining);143+144+ // 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);152+153+ let res = time_shell_command(cmd, options.ignore_failure)?;154+ results.push(res);155+ bar.inc(1);156+ }157+ bar.finish_and_clear();158+159+ // Compute statistical quantities160+161+ // Corrected execution times162+ let execution_times = results.iter().map(&get_execution_time);163+164+ let t_mean = mean(execution_times.clone());165+ let t2_mean = mean(execution_times.clone().map(|t| t.powi(2)));166+167+ let stddev = (t2_mean - t_mean.powi(2)).sqrt();168+169+ // Formatting and console output170+ let time_fmt = format!("{:.3} s ± {:.3} s", t_mean, stddev);171+172+ println!(" Time: {}", Green.paint(time_fmt));173+174+ // Warnings175+ let mut warnings = vec![];176+177+ // Check execution time178+ if execution_times.clone().any(|t| t < MIN_EXECUTION_TIME) {179+ warnings.push(Warnings::FastExecutionTime);180+ }181+182+ // Check programm exit codes183+ if results.iter().any(|r| !r.success) {184+ warnings.push(Warnings::NonZeroExitCode);185+ }186+187+ if warnings.len() > 0 {188+ eprintln!();189+ for warning in &warnings {190+ eprintln!(" {}: {}", Yellow.paint("Warning"), warning);191+ }192+ }193+194+ println!();195+196+ Ok(())197+}added:src/hyperfine/internal.rs+68 added
1+use std::fmt;2+3+use indicatif::{ProgressBar, ProgressStyle};4+5+/// Type alias for unit of time6+pub type Second = f64;7+8+/// Threshold for warning about fast execution time9+pub const MIN_EXECUTION_TIME: Second = 5e-3;10+11+/// A set of options for hyperfine12+pub struct HyperfineOptions {13+ /// Number of warmup runs14+ pub warmup_count: u64,15+16+ /// Minimum number of benchmark runs17+ pub min_runs: u64,18+19+ /// Minimum benchmarking time20+ pub min_time_sec: Second,21+22+ /// Whether or not to ignore non-zero exit codes23+ pub ignore_failure: bool,24+}25+26+impl 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+}36+37+/// Return a pre-configured progress bar38+pub 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}");42+43+ let bar = ProgressBar::new(length);44+ bar.set_style(progressbar_style.clone());45+ bar.enable_steady_tick(80);46+ bar.set_message(msg);47+48+ bar49+}50+51+/// Possible benchmark warnings52+pub enum Warnings {53+ FastExecutionTime,54+ NonZeroExitCode,55+}56+57+impl 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
1+pub mod benchmark;2+pub mod internal;3+pub mod statistics;added:src/hyperfine/statistics.rs+13 added
1+/// Calculate statistical average2+pub fn mean<I>(values: I) -> f643+where4+ 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 lines5 6 use std::cmp;7 use std::error::Error;8 use std::io;9-use std::process::{Command, Stdio};10-use std::time::Instant;11-use std::fmt;9 13-use indicatif::{ProgressBar, ProgressStyle};14-use ansi_term::Colour::{Cyan, Green, Red, White, Yellow};10+use ansi_term::Colour::Red;11 use clap::{App, AppSettings, Arg};12 17-/// Type alias for unit of time18-type Second = f64;13+mod hyperfine;14 20-/// Threshold for warning about fast execution time21-const MIN_EXECUTION_TIME: Second = 5e-3;15+use hyperfine::internal::HyperfineOptions;16+use hyperfine::benchmark::{mean_shell_spawning_time, run_benchmark};17 18 /// Print error message to stderr and terminate19 pub fn error(message: &str) -> ! {20 eprintln!("{}: {}", Red.paint("Error"), message);21 std::process::exit(1);22 }23 29-struct CmdResult {30- /// Execution time in seconds31- execution_time_sec: Second,32-33- /// True if the command finished with exit code zero34- success: bool,35-}36-37-impl CmdResult {38- fn new(execution_time_sec: Second, success: bool) -> CmdResult {39- CmdResult {40- execution_time_sec,41- success,42- }43- }44-}45-46-/// Run the given shell command and measure the execution time47-fn time_shell_command(shell_cmd: &str, ignore_failure: bool) -> io::Result<CmdResult> {48- let start = Instant::now();49-50- 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()?;57-58- 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- }65-66- let duration = start.elapsed();67-68- let execution_time_sec = duration.as_secs() as f64 + duration.subsec_nanos() as f64 * 1e-9;69-70- Ok(CmdResult::new(execution_time_sec, status.success()))71-}72-73-/// Return a pre-configured progress bar74-fn 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}");78-79- let bar = ProgressBar::new(length);80- bar.set_style(progressbar_style.clone());81- bar.enable_steady_tick(80);82- bar.set_message(msg);83-84- bar85-}86-87-/// Possible benchmark warnings88-enum Warnings {89- FastExecutionTime,90- NonZeroExitCode,91-}92-93-impl 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-}105-106-/// Calculate statistical average107-fn mean<I>(values: I) -> f64108-where109- 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-}119-120-/// Run the benchmark for a single shell command121-fn 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- };135-136- println!(137- "{}{}: {}",138- White.bold().paint("Benchmark #"),139- White.bold().paint((num + 1).to_string()),140- Cyan.paint(cmd)141- );142- println!();143-144- let mut results = vec![];145-146- // Warmup phase147- if options.warmup_count > 0 {148- let bar = get_progress_bar(options.warmup_count, "Performing warmup runs");149-150- 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- }156-157- // Set up progress bar (and spinner for initial measurement)158- let bar = get_progress_bar(options.min_runs, "Initial time measurement");159-160- // Initial timing run161- let res = time_shell_command(cmd, options.ignore_failure)?;162-163- // Determine number of benchmark runs164- let runs_in_min_time = (options.min_time_sec / res.execution_time_sec) as u64;165-166- let count = if runs_in_min_time >= options.min_runs {167- runs_in_min_time168- } else {169- options.min_runs170- };171-172- let count_remaining = count - 1;173-174- // Save the first result175- results.push(res);176-177- // Re-configure the progress bar178- bar.set_length(count_remaining);179-180- // 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);188-189- let res = time_shell_command(cmd, options.ignore_failure)?;190- results.push(res);191- bar.inc(1);192- }193- bar.finish_and_clear();194-195- // Compute statistical quantities196-197- // Corrected execution times198- let execution_times = results.iter().map(&get_execution_time);199-200- let t_mean = mean(execution_times.clone());201- let t2_mean = mean(execution_times.clone().map(|t| t.powi(2)));202-203- let stddev = (t2_mean - t_mean.powi(2)).sqrt();204-205- // Formatting and console output206- let time_fmt = format!("{:.3} s ± {:.3} s", t_mean, stddev);207-208- println!(" Time: {}", Green.paint(time_fmt));209-210- // Warnings211- let mut warnings = vec![];212-213- // Check execution time214- if execution_times.clone().any(|t| t < MIN_EXECUTION_TIME) {215- warnings.push(Warnings::FastExecutionTime);216- }217-218- // Check programm exit codes219- if results.iter().any(|r| !r.success) {220- warnings.push(Warnings::NonZeroExitCode);221- }222-223- if warnings.len() > 0 {224- eprintln!();225- for warning in &warnings {226- eprintln!(" {}: {}", Yellow.paint("Warning"), warning);227- }228- }229-230- println!();231-232- Ok(())233-}234-235-// Measure the average shell spawning time236-fn mean_shell_spawning_time() -> io::Result<Second> {237- const COUNT: u64 = 200;238- let bar = get_progress_bar(COUNT, "Measuring shell spawning time");239-240- let mut times: Vec<Second> = vec![];241- for _ in 0..COUNT {242- let res = time_shell_command("", false);243-244- 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();259-260- let mean: f64 = mean(times.iter().cloned()); // TODO: get rid of .cloned()261- Ok(mean)262-}263-24 /// Runs the benchmark for the given commands25 fn run(commands: &Vec<&str>, options: &HyperfineOptions) -> io::Result<()> {26 let shell_spawning_time = mean_shell_spawning_time()?;27 4 unmodified lines32 33 Ok(())34 }35 276-pub struct HyperfineOptions {277- /// Number of warmup runs278- pub warmup_count: u64,279-280- /// Minimum number of benchmark runs281- pub min_runs: u64,282-283- /// Minimum benchmarking time284- pub min_time_sec: Second,285-286- /// Whether or not to ignore non-zero exit codes287- pub ignore_failure: bool,288-}289-290-impl 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-}300-36 fn main() {37 let matches = App::new("hyperfine")38 .version(crate_version!())39 .setting(AppSettings::ColoredHelp)57 unmodified lines