Initial support for user and system time
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by sharkdp · committed by David Peter · parent 35a5139 · Browse files · 6 files·+143 added−50 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
6 files+143 added−50 removed
- other:+143 added−50 removed
Provenance
- Commit
ef2bef5- Tree
472be95- Author
sharkdp <davidpeter@web.de>- Committer
David Peter <sharkdp@users.noreply.github.com>- Parent
35a5139
6 files changed+143 added−50 removed
modified:src/hyperfine/benchmark.rs+88 added-48 removed
1 use std::io;2 use std::process::{Command, Stdio};3 use std::time::Instant;4 5-use ansi_term::Colour::{Cyan, Green, Purple, White, Yellow};5+use ansi_term::Colour::{Blue, Cyan, Green, Purple, White, Yellow};6 use statistical::{mean, standard_deviation};7 8 use hyperfine::internal::{get_progress_bar, max, min, CmdFailureAction, HyperfineOptions, Second,9 Warnings, MIN_EXECUTION_TIME};10 use hyperfine::format::{format_duration, format_duration_unit};11+use hyperfine::cputime::{get_cpu_interval, get_cpu_times};12 13 /// Results from timing a single shell command14+#[derive(Debug, Copy, Clone)]15 pub struct TimingResult {14- /// Execution time in seconds15- pub execution_time: Second,16+ /// Wall clock time17+ pub time_real: Second,18 17- /// True if the command finished with exit code zero18- pub success: bool,19+ /// Time spent in user mode20+ pub time_user: Second,21+22+ /// Time spent in kernel mode23+ pub time_system: Second,24 }25 21-impl TimingResult {22- fn new(execution_time: Second, success: bool) -> TimingResult {23- TimingResult {24- execution_time,25- success,26- }26+/// Correct for shell spawning time27+fn subtract_shell_spawning_time(time: Second, shell_spawning_time: Second) -> Second {28+ if time < shell_spawning_time {29+ 0.030+ } else {31+ time - shell_spawning_time32 }33 }34 35 /// Run the given shell command and measure the execution time36 pub fn time_shell_command(37 shell_cmd: &str,38 failure_action: CmdFailureAction,34- shell_spawning_time: Option<Second>,35-) -> io::Result<TimingResult> {39+ shell_spawning_time: Option<TimingResult>,40+) -> io::Result<(TimingResult, bool)> {41 let start = Instant::now();42+ let start_cpu = get_cpu_times();43 44 let status = Command::new("sh")45 .arg("-c")46 .arg(shell_cmd)1 unmodified line48 .stdout(Stdio::null())49 .stderr(Stdio::null())50 .status()?;51 52+ let end_cpu = get_cpu_times();53+ let duration = start.elapsed();54+55 if failure_action == CmdFailureAction::RaiseError && !status.success() {56 return Err(io::Error::new(57 io::ErrorKind::Other,58 "Command terminated with non-zero exit code. \59 Use the '-i'/'--ignore-failure' option if you want to ignore this.",60 ));61 }62 54- let duration = start.elapsed();63+ // Real time64+ let mut time_real = duration.as_secs() as f64 + (duration.subsec_nanos() as f64) * 1e-9;65 56- let execution_time = duration.as_secs() as f64 + (duration.subsec_nanos() as f64) * 1e-9;66+ // User and system time67+ let cpu_interval = get_cpu_interval(&start_cpu, &end_cpu);68+ let mut time_user = cpu_interval.user;69+ let mut time_system = cpu_interval.system;70 71 // Correct for shell spawning time59- let execution_time_corrected = if let Some(spawning_time) = shell_spawning_time {60- if execution_time < spawning_time {61- 0.062- } else {63- execution_time - spawning_time64- }65- } else {66- execution_time67- };72+ if let Some(spawning_time) = shell_spawning_time {73+ time_real = subtract_shell_spawning_time(time_real, spawning_time.time_real);74+ time_user = subtract_shell_spawning_time(cpu_interval.user, spawning_time.time_user);75+ time_system = subtract_shell_spawning_time(cpu_interval.system, spawning_time.time_system);76+ }77 69- Ok(TimingResult::new(70- execution_time_corrected,78+ Ok((79+ TimingResult {80+ time_real,81+ time_user,82+ time_system,83+ },84 status.success(),85 ))86 }87 88 /// Measure the average shell spawning time76-pub fn mean_shell_spawning_time() -> io::Result<Second> {89+pub fn mean_shell_spawning_time() -> io::Result<TimingResult> {90 const COUNT: u64 = 200;91 let progress_bar = get_progress_bar(COUNT, "Measuring shell spawning time");92 80- let mut times: Vec<Second> = vec![];93+ let mut times_real: Vec<Second> = vec![];94+ let mut times_user: Vec<Second> = vec![];95+ let mut times_system: Vec<Second> = vec![];96+97 for _ in 0..COUNT {98 // Just run the shell without any command99 let res = time_shell_command("", CmdFailureAction::RaiseError, None);100 4 unmodified lines105 "Could not measure shell execution time. \106 Make sure you can run 'sh -c \"\"'.",107 ))108 }93- Ok(r) => {94- times.push(r.execution_time);109+ Ok((r, _)) => {110+ times_real.push(r.time_real);111+ times_user.push(r.time_user);112+ times_system.push(r.time_system);113 }114 }115 progress_bar.inc(1);116 }117 progress_bar.finish_and_clear();118 101- Ok(mean(×))119+ Ok(TimingResult {120+ time_real: mean(×_real),121+ time_user: mean(×_user),122+ time_system: mean(×_system),123+ })124 }125 126 /// Run the benchmark for a single shell command127 pub fn run_benchmark(128 num: usize,129 cmd: &str,108- shell_spawning_time: Second,130+ shell_spawning_time: TimingResult,131 options: &HyperfineOptions,132 ) -> io::Result<()> {133 println!(134 "{}{}: {}",2 unmodified lines137 cmd138 );139 println!();140 119- let mut execution_times: Vec<Second> = vec![];141+ let mut times_real: Vec<Second> = vec![];142+ let mut times_user: Vec<Second> = vec![];143+ let mut times_system: Vec<Second> = vec![];144 let mut all_succeeded = true;145 146 // Warmup phase147 if options.warmup_count > 0 {17 unmodified lines165 };166 run_preparation_command();167 168 // Initial timing run169+ let (res, success) =145- let res = time_shell_command(cmd, options.failure_action, Some(shell_spawning_time))?;170+ time_shell_command(cmd, options.failure_action, Some(shell_spawning_time))?;171 172 // Determine number of benchmark runs173 let runs_in_min_time =149- (options.min_time_sec / (res.execution_time + shell_spawning_time)) as u64;174+ (options.min_time_sec / (res.time_real + shell_spawning_time.time_real)) as u64;175 176 let count = if runs_in_min_time >= options.min_runs {177 runs_in_min_time178 } else {2 unmodified lines181 182 let count_remaining = count - 1;183 184 // Save the first result160- execution_times.push(res.execution_time);161- all_succeeded = all_succeeded && res.success;185+ times_real.push(res.time_real);186+ times_user.push(res.time_user);187+ times_system.push(res.time_system);188 189+ all_succeeded = all_succeeded && success;190+191 // Re-configure the progress bar192 progress_bar.set_length(count_remaining);193 194 // Gather statistics195 for _ in 0..count_remaining {196 run_preparation_command();197 198 let msg = {171- let mean = format_duration(mean(&execution_times), None);199+ let mean = format_duration(mean(×_real), None);200 format!("Current estimate: {}", Green.paint(mean))201 };202 progress_bar.set_message(&msg);203 204+ let (res, success) =176- let res = time_shell_command(cmd, options.failure_action, Some(shell_spawning_time))?;205+ time_shell_command(cmd, options.failure_action, Some(shell_spawning_time))?;206 178- execution_times.push(res.execution_time);179- all_succeeded = all_succeeded && res.success;207+ times_real.push(res.time_real);208+ times_user.push(res.time_user);209+ times_system.push(res.time_system);210 211+ all_succeeded = all_succeeded && success;212+213 progress_bar.inc(1);214 }215 progress_bar.finish_and_clear();216 217 // Compute statistical quantities186- let t_mean = mean(&execution_times);187- let t_stddev = standard_deviation(&execution_times, Some(t_mean));188- let t_min = min(&execution_times);189- let t_max = max(&execution_times);218+ let t_mean = mean(×_real);219+ let t_stddev = standard_deviation(×_real, Some(t_mean));220+ let t_min = min(×_real);221+ let t_max = max(×_real);222 223+ let user_mean = mean(×_user);224+ let system_mean = mean(×_system);225+226 // Formatting and console output227 let (mean_str, unit_mean) = format_duration_unit(t_mean, None);228 let stddev_str = format_duration(t_stddev, Some(unit_mean));229 let min_str = format_duration(t_min, Some(unit_mean));230 let max_str = format_duration(t_max, Some(unit_mean));231 232+ let (user_str, user_unit) = format_duration_unit(user_mean, None);233+ let system_str = format_duration(system_mean, Some(user_unit));234+235 println!(198- " Time ({} ± {}): {} ± {}",236+ " Time ({} ± {}): {} ± {} [User: {}, System: {}]",237 Green.bold().paint("mean"),238 Green.paint("σ"),239 Green.bold().paint(mean_str),202- Green.paint(stddev_str)240+ Green.paint(stddev_str),241+ Blue.paint(user_str),242+ Blue.paint(system_str)243 );244 println!(" ");245 246 println!(7 unmodified lines254 // Warnings255 let mut warnings = vec![];256 257 // Check execution time218- if execution_times.iter().any(|&t| t < MIN_EXECUTION_TIME) {258+ if times_real.iter().any(|&t| t < MIN_EXECUTION_TIME) {259 warnings.push(Warnings::FastExecutionTime);260 }261 262 // Check programm exit codes15 unmodified linesadded:src/hyperfine/cputime.rs+49 added
1+use libc::{getrusage, rusage, RUSAGE_CHILDREN};2+use std::mem;3+4+use hyperfine::internal::Second;5+6+#[derive(Debug, Copy, Clone)]7+pub struct CPUTimes {8+ /// Total amount of time spent executing in user mode9+ user_usec: i64,10+11+ /// Total amount of time spent executing in kernel mode12+ system_usec: i64,13+}14+15+#[derive(Debug, Copy, Clone)]16+pub struct CPUInterval {17+ /// Total amount of time spent executing in user mode18+ pub user: Second,19+20+ /// Total amount of time spent executing in kernel mode21+ pub system: Second,22+}23+24+/// Read CPU execution times (user and system time) from kernel25+pub fn get_cpu_times() -> CPUTimes {26+ let result: rusage = unsafe {27+ let mut buf = mem::zeroed();28+ let success = getrusage(RUSAGE_CHILDREN, &mut buf);29+ assert_eq!(0, success);30+ buf31+ };32+33+ const USEC_PER_SEC: i64 = 1000 * 1000;34+35+ CPUTimes {36+ user_usec: i64::from(result.ru_utime.tv_sec) * USEC_PER_SEC37+ + i64::from(result.ru_utime.tv_usec),38+ system_usec: i64::from(result.ru_stime.tv_sec) * USEC_PER_SEC39+ + i64::from(result.ru_stime.tv_usec),40+ }41+}42+43+/// Compute the time intervals in between two CPUTimes snapshots44+pub fn get_cpu_interval(start: &CPUTimes, end: &CPUTimes) -> CPUInterval {45+ CPUInterval {46+ user: ((end.user_usec - start.user_usec) as f64) * 1e-6,47+ system: ((end.system_usec - start.system_usec) as f64) * 1e-6,48+ }49+}modified:src/hyperfine/mod.rs+1 added
1 pub mod benchmark;2 pub mod format;3 pub mod internal;4+pub mod cputime;modified:src/main.rs+1 added
1 extern crate ansi_term;2 #[macro_use]3 extern crate clap;4 extern crate indicatif;5+extern crate libc;6 extern crate statistical;7 8 use std::cmp;9 use std::error::Error;114 unmodified linesmodified:Cargo.lock+2 added-1 removed
80 unmodified lines81 source = "registry+https://github.com/rust-lang/crates.io-index"82 83 [[package]]84 name = "hyperfine"85-version = "0.2.0"85+version = "0.3.0"86 dependencies = [87 "ansi_term 0.10.2 (registry+https://github.com/rust-lang/crates.io-index)",88 "clap 2.29.2 (registry+https://github.com/rust-lang/crates.io-index)",89 "indicatif 0.9.0 (registry+https://github.com/rust-lang/crates.io-index)",90+ "libc 0.2.36 (registry+https://github.com/rust-lang/crates.io-index)",91 "statistical 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)",92 ]93 94 [[package]]352 unmodified linesmodified:Cargo.toml+2 added-1 removed
5 unmodified lines6789101011121314151617181920215 unmodified lineslicense = "MIT/Apache-2.0"name = "hyperfine"readme = "README.md"repository = "https://github.com/sharkdp/hyperfine"version = "0.2.0"version = "0.3.0"
[dependencies]ansi_term = "0.10"indicatif = "0.9"statistical = "0.1"libc = "0.2"
[dependencies.clap]version = "2"default-features = falsefeatures = ["suggestions", "color", "wrap_help"]