Skip to content
Myr

Initial work on refactoring

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 eb92bd4 · Browse files · 7 files+174 added−161 removed
This commit

State

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

Diff stats

7 files+174 added−161 removed

  • other:+174 added−161 removed

7 files+174 added−161 removed

added:src/hyperfine/timer/cputimer.rs+97 added
1use std::mem;23use hyperfine::internal::Second;4use hyperfine::timer::Timer;56#[derive(Debug, Copy, Clone)]7struct 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)]16struct 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')25fn get_cpu_times() -> CPUTimes {26 use libc::{getrusage, rusage, RUSAGE_CHILDREN};2728 let result: rusage = unsafe {29 let mut buf = mem::zeroed();30 let success = getrusage(RUSAGE_CHILDREN, &mut buf);31 assert_eq!(0, success);32 buf33 };3435 const MICROSEC_PER_SEC: i64 = 1000 * 1000;3637 CPUTimes {38 user_usec: i64::from(result.ru_utime.tv_sec) * MICROSEC_PER_SEC39 + i64::from(result.ru_utime.tv_usec),40 system_usec: i64::from(result.ru_stime.tv_sec) * MICROSEC_PER_SEC41 + i64::from(result.ru_stime.tv_usec),42 }43}4445/// Compute the time intervals in between two `CPUTimes` snapshots46fn cpu_time_interval(start: &CPUTimes, end: &CPUTimes) -> CPUInterval {47 CPUInterval {48 user: ((end.user_usec - start.user_usec) as f64) * 1e-6,49 system: ((end.system_usec - start.system_usec) as f64) * 1e-6,50 }51}5253/// A timer that measures system and user time54pub struct CPUTimer {55 start_cpu: CPUTimes,56}5758impl Timer for CPUTimer {59 type Result = (Second, Second);6061 fn start() -> Self {62 CPUTimer {63 start_cpu: get_cpu_times(),64 }65 }6667 fn stop(&self) -> Self::Result {68 let end_cpu = get_cpu_times();69 let cpu_interval = cpu_time_interval(&self.start_cpu, &end_cpu);70 (cpu_interval.user, cpu_interval.system)71 }72}7374#[test]75fn test_cpu_time_interval() {76 let t_a = CPUTimes {77 user_usec: 12345,78 system_usec: 54321,79 };8081 let t_b = CPUTimes {82 user_usec: 20000,83 system_usec: 70000,84 };8586 let t_zero = cpu_time_interval(&t_a, &t_a);87 assert_eq!(0.0, t_zero.user);88 assert_eq!(0.0, t_zero.system);8990 let t_ab = cpu_time_interval(&t_a, &t_b);91 assert_relative_eq!(0.007655, t_ab.user);92 assert_relative_eq!(0.015679, t_ab.system);9394 let t_ba = cpu_time_interval(&t_b, &t_a);95 assert_relative_eq!(-0.007655, t_ba.user);96 assert_relative_eq!(-0.015679, t_ba.system);97}
added:src/hyperfine/timer/mod.rs+10 added
1pub mod wallclocktimer;2pub mod cputimer;34/// Defines a general timer with start/stop functionality.5pub trait Timer {6 type Result;78 fn start() -> Self;9 fn stop(&self) -> Self::Result;10}
added:src/hyperfine/timer/wallclocktimer.rs+23 added
1use std::time::Instant;23use hyperfine::internal::Second;4use hyperfine::timer::Timer;56pub struct WallClockTimer {7 start: Instant,8}910impl Timer for WallClockTimer {11 type Result = Second;1213 fn start() -> WallClockTimer {14 WallClockTimer {15 start: Instant::now(),16 }17 }1819 fn stop(&self) -> Second {20 let duration = self.start.elapsed();21 duration.as_secs() as f64 + (duration.subsec_nanos() as f64) * 1e-922 }23}
modified:src/hyperfine/benchmark.rs+17 added-81 removed
1use std::io;2use std::process::{Command, ExitStatus, Stdio};3use std::time::Instant;23use colored::*;4use statistical::{mean, standard_deviation};5
1 unmodified line
7 OutputStyleOption, Second, MIN_EXECUTION_TIME};8use hyperfine::warnings::Warnings;9use hyperfine::format::{format_duration, format_duration_unit};10use hyperfine::outlier_detection::{modified_zscores, OUTLIER_THRESHOLD};11use hyperfine::timer::Timer;12use hyperfine::timer::wallclocktimer::WallClockTimer;13use hyperfine::timer::cputimer::CPUTimer;14use hyperfine::shell::run_shell_command;1514#[cfg(not(target_os = "windows"))]15use hyperfine::cputime::{cpu_time_interval, get_cpu_times};1616/// Results from timing a single shell command17#[derive(Debug, Copy, Clone)]18pub struct TimingResult {19 /// Wall clock time
20 unmodified lines
40 shell_cmd: &str,41 failure_action: CmdFailureAction,42 shell_spawning_time: Option<TimingResult>,43) -> io::Result<(TimingResult, bool)> {45 let start = Instant::now();46 let timer = cpu_interval_timer();44 let wallclock_timer = WallClockTimer::start();45 let cpu_timer = CPUTimer::start();4647 let status = run_shell_command(shell_cmd)?;4850 let (mut time_user, mut time_system) = timer();51 let duration = start.elapsed();49 let mut time_real = wallclock_timer.stop();50 let (mut time_user, mut time_system) = cpu_timer.stop();5152 if failure_action == CmdFailureAction::RaiseError && !status.success() {53 return Err(io::Error::new(54 io::ErrorKind::Other,
1 unmodified line
56 Use the '-i'/'--ignore-failure' option if you want to ignore this.",57 ));58 }5961 // Real time62 let mut time_real = duration.as_secs() as f64 + (duration.subsec_nanos() as f64) * 1e-9;6360 // Correct for shell spawning time61 if let Some(spawning_time) = shell_spawning_time {62 time_real = subtract_shell_spawning_time(time_real, spawning_time.time_real);63 time_user = subtract_shell_spawning_time(time_user, spawning_time.time_user);
47 unmodified lines
111 time_system: mean(&times_system),112 })113}114119/// Retrieve a timer Fn that starts on the initial call and stops when the120/// returned closure is called.121#[cfg(not(target_os = "windows"))]122fn cpu_interval_timer() -> Box<Fn() -> (f64, f64)> {123 let start_cpu = get_cpu_times();124 let timer = move || {125 let end_cpu = get_cpu_times();126 let cpu_interval = cpu_time_interval(&start_cpu, &end_cpu);127 (cpu_interval.user, cpu_interval.system)128 };129130 Box::new(timer)131}132133/// Return a timer Fn that will always return (0,0) when called134#[cfg(target_os = "windows")]135fn cpu_interval_timer() -> Box<Fn() -> (f64, f64)> {136 Box::new(|| (0f64, 0f64))137}138139/// Run a standard sh command140#[cfg(not(target_os = "windows"))]141fn run_shell_command(command: &str) -> io::Result<ExitStatus> {142 Command::new("sh")143 .arg("-c")144 .arg(command)145 .stdin(Stdio::null())146 .stdout(Stdio::null())147 .stderr(Stdio::null())148 .status()149}150151/// Run a Windows command using cmd152#[cfg(target_os = "windows")]153fn run_shell_command(command: &str) -> io::Result<ExitStatus> {154 Command::new("cmd")155 .arg(command)156 .stdin(Stdio::null())157 .stdout(Stdio::null())158 .stderr(Stdio::null())159 .status()160}161115/// Run the command specified by `--prepare`.116fn run_preparation_command(command: &Option<String>) -> io::Result<()> {117 if let &Some(ref preparation_command) = command {118 let res = time_shell_command(preparation_command, CmdFailureAction::RaiseError, None);
119 unmodified lines
238239 let (user_str, user_unit) = format_duration_unit(user_mean, None);240 let system_str = format_duration(system_mean, Some(user_unit));241289 output_times(mean_str, stddev_str, user_str, system_str);290242 println!(243 " Time ({} ± {}): {:>8} ± {:>8} [User: {}, System: {}]",244 "mean".green().bold(),245 "σ".green(),246 mean_str.green().bold(),247 stddev_str.green(),248 user_str.blue(),249 system_str.blue()250 );251 println!(" ");252253 println!(254 " Range ({} … {}): {:>8} … {:>8}",
35 unmodified lines
290 println!(" ");291292 Ok(())293}334335#[cfg(not(target_os = "windows"))]336fn output_times(mean_str: String, stddev_str: String, user_str: String, system_str: String) {337 println!(338 " Time ({} ± {}): {:>8} ± {:>8} [User: {}, System: {}]",339 "mean".green().bold(),340 "σ".green(),341 mean_str.green().bold(),342 stddev_str.green(),343 user_str.blue(),344 system_str.blue()345 );346}347348#[cfg(target_os = "windows")]349fn output_times(mean_str: String, stddev_str: String, _user_str: String, _system_str: String) {350 println!(351 " Time ({} ± {}): {:>8} ± {:>8}",352 "mean".green().bold(),353 "σ".green(),354 mean_str.green().bold(),355 stddev_str.green(),356 );357}
deleted:src/hyperfine/cputime.rs-77 removed
1#![cfg(not(target_os = "windows"))]23use libc::{getrusage, rusage, RUSAGE_CHILDREN};45use std::mem;67use hyperfine::internal::Second;89#[derive(Debug, Copy, Clone)]10pub struct CPUTimes {11 /// Total amount of time spent executing in user mode12 user_usec: i64,1314 /// Total amount of time spent executing in kernel mode15 system_usec: i64,16}1718#[derive(Debug, Copy, Clone)]19pub struct CPUInterval {20 /// Total amount of time spent executing in user mode21 pub user: Second,2223 /// Total amount of time spent executing in kernel mode24 pub system: Second,25}2627/// Read CPU execution times ('user' and 'system')28pub fn get_cpu_times() -> CPUTimes {29 let result: rusage = unsafe {30 let mut buf = mem::zeroed();31 let success = getrusage(RUSAGE_CHILDREN, &mut buf);32 assert_eq!(0, success);33 buf34 };3536 const MICROSEC_PER_SEC: i64 = 1000 * 1000;3738 CPUTimes {39 user_usec: i64::from(result.ru_utime.tv_sec) * MICROSEC_PER_SEC40 + i64::from(result.ru_utime.tv_usec),41 system_usec: i64::from(result.ru_stime.tv_sec) * MICROSEC_PER_SEC42 + i64::from(result.ru_stime.tv_usec),43 }44}4546/// Compute the time intervals in between two `CPUTimes` snapshots47pub fn cpu_time_interval(start: &CPUTimes, end: &CPUTimes) -> CPUInterval {48 CPUInterval {49 user: ((end.user_usec - start.user_usec) as f64) * 1e-6,50 system: ((end.system_usec - start.system_usec) as f64) * 1e-6,51 }52}5354#[test]55fn test_cpu_time_interval() {56 let t_a = CPUTimes {57 user_usec: 12345,58 system_usec: 54321,59 };6061 let t_b = CPUTimes {62 user_usec: 20000,63 system_usec: 70000,64 };6566 let t_zero = cpu_time_interval(&t_a, &t_a);67 assert_eq!(0.0, t_zero.user);68 assert_eq!(0.0, t_zero.system);6970 let t_ab = cpu_time_interval(&t_a, &t_b);71 assert_relative_eq!(0.007655, t_ab.user);72 assert_relative_eq!(0.015679, t_ab.system);7374 let t_ba = cpu_time_interval(&t_b, &t_a);75 assert_relative_eq!(-0.007655, t_ba.user);76 assert_relative_eq!(-0.015679, t_ba.system);77}
modified:src/hyperfine/mod.rs+2 added-3 removed
1 unmodified line
2pub mod format;3pub mod internal;4pub mod outlier_detection;5pub mod warnings;67#[cfg(not(target_os = "windows"))]8pub mod cputime;6pub mod timer;7pub mod shell;
added:src/hyperfine/shell.rs+25 added
1use std::io;2use std::process::{Command, ExitStatus, Stdio};34/// Run a standard shell command5#[cfg(not(target_os = "windows"))]6pub fn run_shell_command(command: &str) -> io::Result<ExitStatus> {7 Command::new("sh")8 .arg("-c")9 .arg(command)10 .stdin(Stdio::null())11 .stdout(Stdio::null())12 .stderr(Stdio::null())13 .status()14}1516/// Run a Windows shell command using cmd.exe17#[cfg(target_os = "windows")]18pub fn run_shell_command(command: &str) -> io::Result<ExitStatus> {19 Command::new("cmd")20 .arg(command)21 .stdin(Stdio::null())22 .stdout(Stdio::null())23 .stderr(Stdio::null())24 .status()25}