Skip to content
Myr

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

6 files+143 added−50 removed

modified:src/hyperfine/benchmark.rs+88 added-48 removed
1use std::io;2use std::process::{Command, Stdio};3use std::time::Instant;45use ansi_term::Colour::{Cyan, Green, Purple, White, Yellow};5use ansi_term::Colour::{Blue, Cyan, Green, Purple, White, Yellow};6use statistical::{mean, standard_deviation};78use hyperfine::internal::{get_progress_bar, max, min, CmdFailureAction, HyperfineOptions, Second,9 Warnings, MIN_EXECUTION_TIME};10use hyperfine::format::{format_duration, format_duration_unit};11use hyperfine::cputime::{get_cpu_interval, get_cpu_times};1213/// Results from timing a single shell command14#[derive(Debug, Copy, Clone)]15pub struct TimingResult {14 /// Execution time in seconds15 pub execution_time: Second,16 /// Wall clock time17 pub time_real: Second,1817 /// True if the command finished with exit code zero18 pub success: bool,19 /// Time spent in user mode20 pub time_user: Second,2122 /// Time spent in kernel mode23 pub time_system: Second,24}2521impl TimingResult {22 fn new(execution_time: Second, success: bool) -> TimingResult {23 TimingResult {24 execution_time,25 success,26 }26/// Correct for shell spawning time27fn 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}3435/// Run the given shell command and measure the execution time36pub 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();4344 let status = Command::new("sh")45 .arg("-c")46 .arg(shell_cmd)
1 unmodified line
48 .stdout(Stdio::null())49 .stderr(Stdio::null())50 .status()?;5152 let end_cpu = get_cpu_times();53 let duration = start.elapsed();5455 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 }6254 let duration = start.elapsed();63 // Real time64 let mut time_real = duration.as_secs() as f64 + (duration.subsec_nanos() as f64) * 1e-9;6556 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;7071 // 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 }7769 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}8788/// Measure the average shell spawning time76pub fn mean_shell_spawning_time() -> io::Result<Second> {89pub 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");9280 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![];9697 for _ in 0..COUNT {98 // Just run the shell without any command99 let res = time_shell_command("", CmdFailureAction::RaiseError, None);100
4 unmodified lines
105 "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();118101 Ok(mean(&times))119 Ok(TimingResult {120 time_real: mean(&times_real),121 time_user: mean(&times_user),122 time_system: mean(&times_system),123 })124}125126/// Run the benchmark for a single shell command127pub 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 lines
137 cmd138 );139 println!();140119 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;145146 // Warmup phase147 if options.warmup_count > 0 {
17 unmodified lines
165 };166 run_preparation_command();167168 // 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))?;171172 // 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;175176 let count = if runs_in_min_time >= options.min_runs {177 runs_in_min_time178 } else {
2 unmodified lines
181182 let count_remaining = count - 1;183184 // 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);188189 all_succeeded = all_succeeded && success;190191 // Re-configure the progress bar192 progress_bar.set_length(count_remaining);193194 // Gather statistics195 for _ in 0..count_remaining {196 run_preparation_command();197198 let msg = {171 let mean = format_duration(mean(&execution_times), None);199 let mean = format_duration(mean(&times_real), None);200 format!("Current estimate: {}", Green.paint(mean))201 };202 progress_bar.set_message(&msg);203204 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))?;206178 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);210211 all_succeeded = all_succeeded && success;212213 progress_bar.inc(1);214 }215 progress_bar.finish_and_clear();216217 // 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(&times_real);219 let t_stddev = standard_deviation(&times_real, Some(t_mean));220 let t_min = min(&times_real);221 let t_max = max(&times_real);222223 let user_mean = mean(&times_user);224 let system_mean = mean(&times_system);225226 // 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));231232 let (user_str, user_unit) = format_duration_unit(user_mean, None);233 let system_str = format_duration(system_mean, Some(user_unit));234235 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!(" ");245246 println!(
7 unmodified lines
254 // Warnings255 let mut warnings = vec![];256257 // 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 }261262 // Check programm exit codes
15 unmodified lines
added:src/hyperfine/cputime.rs+49 added
1use libc::{getrusage, rusage, RUSAGE_CHILDREN};2use std::mem;34use hyperfine::internal::Second;56#[derive(Debug, Copy, Clone)]7pub struct CPUTimes {8 /// Total amount of time spent executing in user mode9 user_usec: i64,1011 /// Total amount of time spent executing in kernel mode12 system_usec: i64,13}1415#[derive(Debug, Copy, Clone)]16pub struct CPUInterval {17 /// Total amount of time spent executing in user mode18 pub user: Second,1920 /// Total amount of time spent executing in kernel mode21 pub system: Second,22}2324/// Read CPU execution times (user and system time) from kernel25pub 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 };3233 const USEC_PER_SEC: i64 = 1000 * 1000;3435 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}4243/// Compute the time intervals in between two CPUTimes snapshots44pub 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
1pub mod benchmark;2pub mod format;3pub mod internal;4pub mod cputime;
modified:src/main.rs+1 added
1extern crate ansi_term;2#[macro_use]3extern crate clap;4extern crate indicatif;5extern crate libc;6extern crate statistical;78use std::cmp;9use std::error::Error;
114 unmodified lines
modified:Cargo.lock+2 added-1 removed
80 unmodified lines
81source = "registry+https://github.com/rust-lang/crates.io-index"8283[[package]]84name = "hyperfine"85version = "0.2.0"85version = "0.3.0"86dependencies = [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]9394[[package]]
352 unmodified lines
modified:Cargo.toml+2 added-1 removed