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
Provenance
- Commit
fefb3f2- Tree
6161d3d- Author
sharkdp <davidpeter@web.de>- Committer
David Peter <sharkdp@users.noreply.github.com>- Parent
eb92bd4
7 files changed+174 added−161 removed
added:src/hyperfine/timer/cputimer.rs+97 added
1+use std::mem;2+3+use hyperfine::internal::Second;4+use hyperfine::timer::Timer;5+6+#[derive(Debug, Copy, Clone)]7+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+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')25+fn get_cpu_times() -> CPUTimes {26+ use libc::{getrusage, rusage, RUSAGE_CHILDREN};27+28+ 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+ };34+35+ const MICROSEC_PER_SEC: i64 = 1000 * 1000;36+37+ 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+}44+45+/// Compute the time intervals in between two `CPUTimes` snapshots46+fn 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+}52+53+/// A timer that measures system and user time54+pub struct CPUTimer {55+ start_cpu: CPUTimes,56+}57+58+impl Timer for CPUTimer {59+ type Result = (Second, Second);60+61+ fn start() -> Self {62+ CPUTimer {63+ start_cpu: get_cpu_times(),64+ }65+ }66+67+ 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+}73+74+#[test]75+fn test_cpu_time_interval() {76+ let t_a = CPUTimes {77+ user_usec: 12345,78+ system_usec: 54321,79+ };80+81+ let t_b = CPUTimes {82+ user_usec: 20000,83+ system_usec: 70000,84+ };85+86+ 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);89+90+ 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);93+94+ 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
1+pub mod wallclocktimer;2+pub mod cputimer;3+4+/// Defines a general timer with start/stop functionality.5+pub trait Timer {6+ type Result;7+8+ fn start() -> Self;9+ fn stop(&self) -> Self::Result;10+}added:src/hyperfine/timer/wallclocktimer.rs+23 added
1+use std::time::Instant;2+3+use hyperfine::internal::Second;4+use hyperfine::timer::Timer;5+6+pub struct WallClockTimer {7+ start: Instant,8+}9+10+impl Timer for WallClockTimer {11+ type Result = Second;12+13+ fn start() -> WallClockTimer {14+ WallClockTimer {15+ start: Instant::now(),16+ }17+ }18+19+ 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
1 use std::io;2-use std::process::{Command, ExitStatus, Stdio};3-use std::time::Instant;2 3 use colored::*;4 use statistical::{mean, standard_deviation};5 1 unmodified line7 OutputStyleOption, Second, MIN_EXECUTION_TIME};8 use hyperfine::warnings::Warnings;9 use hyperfine::format::{format_duration, format_duration_unit};10 use hyperfine::outlier_detection::{modified_zscores, OUTLIER_THRESHOLD};11+use hyperfine::timer::Timer;12+use hyperfine::timer::wallclocktimer::WallClockTimer;13+use hyperfine::timer::cputimer::CPUTimer;14+use hyperfine::shell::run_shell_command;15 14-#[cfg(not(target_os = "windows"))]15-use hyperfine::cputime::{cpu_time_interval, get_cpu_times};16-16 /// Results from timing a single shell command17 #[derive(Debug, Copy, Clone)]18 pub struct TimingResult {19 /// Wall clock time20 unmodified lines40 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();46 47 let status = run_shell_command(shell_cmd)?;48 50- 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();51 52 if failure_action == CmdFailureAction::RaiseError && !status.success() {53 return Err(io::Error::new(54 io::ErrorKind::Other,1 unmodified line56 Use the '-i'/'--ignore-failure' option if you want to ignore this.",57 ));58 }59 61- // Real time62- let mut time_real = duration.as_secs() as f64 + (duration.subsec_nanos() as f64) * 1e-9;63-60 // 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 lines111 time_system: mean(×_system),112 })113 }114 119-/// Retrieve a timer Fn that starts on the initial call and stops when the120-/// returned closure is called.121-#[cfg(not(target_os = "windows"))]122-fn 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- };129-130- Box::new(timer)131-}132-133-/// Return a timer Fn that will always return (0,0) when called134-#[cfg(target_os = "windows")]135-fn cpu_interval_timer() -> Box<Fn() -> (f64, f64)> {136- Box::new(|| (0f64, 0f64))137-}138-139-/// Run a standard sh command140-#[cfg(not(target_os = "windows"))]141-fn 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-}150-151-/// Run a Windows command using cmd152-#[cfg(target_os = "windows")]153-fn 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-}161-115 /// Run the command specified by `--prepare`.116 fn 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 lines238 239 let (user_str, user_unit) = format_duration_unit(user_mean, None);240 let system_str = format_duration(system_mean, Some(user_unit));241 289- output_times(mean_str, stddev_str, user_str, system_str);290-242+ 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!(" ");252 253 println!(254 " Range ({} … {}): {:>8} … {:>8}",35 unmodified lines290 println!(" ");291 292 Ok(())293 }334-335-#[cfg(not(target_os = "windows"))]336-fn 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-}347-348-#[cfg(target_os = "windows")]349-fn 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"))]2-3-use libc::{getrusage, rusage, RUSAGE_CHILDREN};4-5-use std::mem;6-7-use hyperfine::internal::Second;8-9-#[derive(Debug, Copy, Clone)]10-pub struct CPUTimes {11- /// Total amount of time spent executing in user mode12- user_usec: i64,13-14- /// Total amount of time spent executing in kernel mode15- system_usec: i64,16-}17-18-#[derive(Debug, Copy, Clone)]19-pub struct CPUInterval {20- /// Total amount of time spent executing in user mode21- pub user: Second,22-23- /// Total amount of time spent executing in kernel mode24- pub system: Second,25-}26-27-/// Read CPU execution times ('user' and 'system')28-pub 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- };35-36- const MICROSEC_PER_SEC: i64 = 1000 * 1000;37-38- 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-}45-46-/// Compute the time intervals in between two `CPUTimes` snapshots47-pub 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-}53-54-#[test]55-fn test_cpu_time_interval() {56- let t_a = CPUTimes {57- user_usec: 12345,58- system_usec: 54321,59- };60-61- let t_b = CPUTimes {62- user_usec: 20000,63- system_usec: 70000,64- };65-66- 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);69-70- 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);73-74- 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 line2 pub mod format;3 pub mod internal;4 pub mod outlier_detection;5 pub mod warnings;6-7-#[cfg(not(target_os = "windows"))]8-pub mod cputime;6+pub mod timer;7+pub mod shell;added:src/hyperfine/shell.rs+25 added
1+use std::io;2+use std::process::{Command, ExitStatus, Stdio};3+4+/// Run a standard shell command5+#[cfg(not(target_os = "windows"))]6+pub 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+}15+16+/// Run a Windows shell command using cmd.exe17+#[cfg(target_os = "windows")]18+pub 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+}