Compare commits

..
Author SHA1 Message Date
David Peter 49691cf483 Extract common functionality 2022-02-22 13:09:56 +01:00
David Peter cd5067eda1 Simplify 2022-02-22 13:01:39 +01:00
David Peter 5f4cddf138 Rename to TimerResult 2022-02-22 12:56:56 +01:00
David Peter 62bfc428a7 Move wall clock timer into execute_and_measure 2022-02-22 12:56:04 +01:00
David Peter 02bbb4e78f Change argument order 2022-02-22 11:57:22 +01:00
David Peter 7a7bcbcc3e Add integration test for --show-output 2022-02-22 11:57:05 +01:00
David Peter 11921b9391 Move Stdio extraction to enum 2022-02-22 11:54:00 +01:00
David Peter 8955006508 Further simplify execute_and_measure 2022-02-22 11:45:46 +01:00
David Peter 57957ff731 Move to timer module 2022-02-22 11:34:30 +01:00
David Peter f1ccef306f Move custom functionality to executor 2022-02-22 11:23:53 +01:00
David Peter 7c264d3662 Rename functions 2022-02-22 11:11:49 +01:00
David Peter 2af99b76d6 Rename to run_command_and_measure 2022-02-22 10:59:33 +01:00
David Peter 45c07323e1 Rename to get_command_line 2022-02-22 10:55:58 +01:00
David Peter defafdf707 Refactor timer module 2022-02-22 10:51:06 +01:00
David Peter f029a46ff9 Fix clippy warnings 2022-02-22 10:13:06 +01:00
David Peter b6ff23a77f Update outdated comment 2022-02-22 10:08:15 +01:00
David Peter eb72702956 Update LICENSE 2022-02-22 10:05:04 +01:00
David Peter 197e5df9f0 Add environment randomization on Windows 2022-02-22 09:42:31 +01:00
David Peter cb6f2f7c4e Remove comment 2022-02-22 09:15:40 +01:00
David Peter 62e82a9b4b Update CHANGELOG 2022-02-22 09:15:25 +01:00
David Peter 6887835f34 Proper shell overhead computation 2022-02-22 09:07:40 +01:00
David Peter 6f51232a8a Add debug/mock mode 2022-02-22 09:07:40 +01:00
David Peter 3348b37b8e Faster tests 2022-02-22 09:07:40 +01:00
David Peter c0ce6b9537 Add integration test for '--shell' 2022-02-22 09:07:40 +01:00
David Peter 5c9c8c2383 New Benchmark struct 2022-02-22 09:07:40 +01:00
David Peter d3c7c7974a Improve error message 2022-02-22 09:07:40 +01:00
David Peter 701a38323d Formatting 2022-02-22 09:07:40 +01:00
David Peter 8c5ae87ca2 Better error handling in run_intermediate_command 2022-02-22 09:07:40 +01:00
David Peter 662d5ca9ac Restructure run_intermediate_command 2022-02-22 09:07:40 +01:00
David Peter f4ef945923 Update BenchmarkResult documentation 2022-02-22 09:07:40 +01:00
David Peter 021583b89b Simplify code 2022-02-22 09:07:40 +01:00
David Peter 0b5ad72872 Rename to command 2022-02-22 09:07:40 +01:00
David Peter 4cfccf1168 Rename num 2022-02-22 09:07:40 +01:00
David Peter fa2eaaac5f Move functionality into run_cleanup_command 2022-02-22 09:07:40 +01:00
David Peter ffa1c0e839 Remove more function arguments 2022-02-22 09:07:40 +01:00
David Peter 39c7736095 Move functions into Scheduler 2022-02-22 09:07:40 +01:00
David Peter dcfeede18e Move functionality to scheduler 2022-02-22 09:07:40 +01:00
David Peter b658e20110 Move exit code function to separate file 2022-02-22 09:07:40 +01:00
David Peter 811e6b5fcd Rename test 2022-02-22 09:07:40 +01:00
David Peter 6645fa10b9 Use get_program 2022-02-22 09:07:40 +01:00
David Peter 21f76a338f Remove unused option 2022-02-22 09:07:40 +01:00
David Peter f9e62e5e7f Rename parse to from_str 2022-02-22 09:07:40 +01:00
David Peter 0ebd76dfc2 Turn show_output into enum 2022-02-22 09:07:40 +01:00
David Peter f9334e15fc Rename _res to _result 2022-02-22 09:07:40 +01:00
David Peter bea0cfab30 Rename Runs to RunBounds 2022-02-22 09:07:40 +01:00
David Peter 250db61fa0 Fix clippy warning 2022-02-22 09:07:40 +01:00
16 changed files with 190 additions and 250 deletions

No files matched your search

+5
View File
@@ -9,11 +9,16 @@
- Breaking change: the `-s` short option for `--style` is now used for - Breaking change: the `-s` short option for `--style` is now used for
the new `--setup` option. the new `--setup` option.
- The environment offset randomization is now also available on Windows,
see #484
## Bugfixes ## Bugfixes
## Other ## Other
- Improved documentation and test coverage, cleaned up code base for
future improvements.
## Packaging ## Packaging
+1 -1
View File
@@ -1,6 +1,6 @@
MIT License MIT License
Copyright (c) 2018-2020 The hyperfine developers Copyright (c) 2018-2022 David Peter, and all hyperfine contributors
Permission is hereby granted, free of charge, to any person obtaining a copy Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal of this software and associated documentation files (the "Software"), to deal
+64 -49
View File
@@ -3,28 +3,67 @@ use std::process::{ExitStatus, Stdio};
use crate::command::Command; use crate::command::Command;
use crate::options::{CmdFailureAction, CommandOutputPolicy, Options, OutputStyleOption, Shell}; use crate::options::{CmdFailureAction, CommandOutputPolicy, Options, OutputStyleOption, Shell};
use crate::output::progress_bar::get_progress_bar; use crate::output::progress_bar::get_progress_bar;
use crate::shell::execute_and_time; use crate::timer::{execute_and_measure, TimerResult};
use crate::timer::wallclocktimer::WallClockTimer; use crate::util::randomized_environment_offset;
use crate::timer::{TimerStart, TimerStop};
use crate::util::units::Second; use crate::util::units::Second;
use super::timing_result::TimingResult; use super::timing_result::TimingResult;
use anyhow::{bail, Result}; use anyhow::{bail, Context, Result};
use statistical::mean; use statistical::mean;
pub trait Executor { pub trait Executor {
fn time_command( /// Run the given command and measure the execution time
fn run_command_and_measure(
&self, &self,
command: &Command<'_>, command: &Command<'_>,
command_failure_action: Option<CmdFailureAction>, command_failure_action: Option<CmdFailureAction>,
) -> Result<(TimingResult, ExitStatus)>; ) -> Result<(TimingResult, ExitStatus)>;
/// Perform a calibration of this executor. For example,
/// when running commands through a shell, we need to
/// measure the shell spawning time separately in order
/// to subtract it from the full runtime later.
fn calibrate(&mut self) -> Result<()>; fn calibrate(&mut self) -> Result<()>;
/// Return the time overhead for this executor when
/// performing a measurement. This should return the time
/// that is being used in addition to the actual runtime
/// of the command.
fn time_overhead(&self) -> Second; fn time_overhead(&self) -> Second;
} }
fn run_command_and_measure_common(
mut command: std::process::Command,
command_failure_action: CmdFailureAction,
command_output_policy: CommandOutputPolicy,
command_name: &str,
) -> Result<TimerResult> {
let (stdout, stderr) = command_output_policy.get_stdout_stderr();
command.stdin(Stdio::null()).stdout(stdout).stderr(stderr);
command.env(
"HYPERFINE_RANDOMIZED_ENVIRONMENT_OFFSET",
randomized_environment_offset::value(),
);
let result = execute_and_measure(command)
.with_context(|| format!("Failed to run command '{}'", command_name))?;
if command_failure_action == CmdFailureAction::RaiseError && !result.status.success() {
bail!(
"{}. Use the '-i'/'--ignore-failure' option if you want to ignore this. \
Alternatively, use the '--show-output' option to debug what went wrong.",
result.status.code().map_or(
"The process has been terminated by a signal".into(),
|c| format!("Command terminated with non-zero exit code: {}", c)
)
);
}
Ok(result)
}
pub struct ShellExecutor<'a> { pub struct ShellExecutor<'a> {
options: &'a Options, options: &'a Options,
shell: &'a Shell, shell: &'a Shell,
@@ -32,15 +71,6 @@ pub struct ShellExecutor<'a> {
} }
impl<'a> ShellExecutor<'a> { impl<'a> ShellExecutor<'a> {
/// Correct for shell spawning time
fn subtract_shell_spawning_time(&self, time: Second, shell_spawning_time: Second) -> Second {
if time < shell_spawning_time {
0.0
} else {
time - shell_spawning_time
}
}
pub fn new(shell: &'a Shell, options: &'a Options) -> Self { pub fn new(shell: &'a Shell, options: &'a Options) -> Self {
ShellExecutor { ShellExecutor {
shell, shell,
@@ -51,50 +81,35 @@ impl<'a> ShellExecutor<'a> {
} }
impl<'a> Executor for ShellExecutor<'a> { impl<'a> Executor for ShellExecutor<'a> {
/// Run the given shell command and measure the execution time fn run_command_and_measure(
fn time_command(
&self, &self,
command: &Command<'_>, command: &Command<'_>,
command_failure_action: Option<CmdFailureAction>, command_failure_action: Option<CmdFailureAction>,
) -> Result<(TimingResult, ExitStatus)> { ) -> Result<(TimingResult, ExitStatus)> {
let (stdout, stderr) = match self.options.command_output_policy { let mut command_builder = self.shell.command();
CommandOutputPolicy::Discard => (Stdio::null(), Stdio::null()), command_builder
CommandOutputPolicy::Forward => (Stdio::inherit(), Stdio::inherit()), .arg(if cfg!(windows) { "/C" } else { "-c" })
}; .arg(command.get_command_line());
let wallclock_timer = WallClockTimer::start(); let mut result = run_command_and_measure_common(
let result = execute_and_time(stdout, stderr, &command.get_shell_command(), &self.shell)?; command_builder,
let mut time_real = wallclock_timer.stop(); command_failure_action.unwrap_or(self.options.command_failure_action),
self.options.command_output_policy,
let mut time_user = result.user_time; &command.get_command_line(),
let mut time_system = result.system_time; )?;
if command_failure_action.unwrap_or(self.options.command_failure_action)
== CmdFailureAction::RaiseError
&& !result.status.success()
{
bail!(
"{}. Use the '-i'/'--ignore-failure' option if you want to ignore this. \
Alternatively, use the '--show-output' option to debug what went wrong.",
result.status.code().map_or(
"The process has been terminated by a signal".into(),
|c| format!("Command terminated with non-zero exit code: {}", c)
)
);
}
// Subtract shell spawning time // Subtract shell spawning time
if let Some(spawning_time) = self.shell_spawning_time { if let Some(spawning_time) = self.shell_spawning_time {
time_real = self.subtract_shell_spawning_time(time_real, spawning_time.time_real); result.time_real = (result.time_real - spawning_time.time_real).max(0.0);
time_user = self.subtract_shell_spawning_time(time_user, spawning_time.time_user); result.time_user = (result.time_user - spawning_time.time_user).max(0.0);
time_system = self.subtract_shell_spawning_time(time_system, spawning_time.time_system); result.time_system = (result.time_system - spawning_time.time_system).max(0.0);
} }
Ok(( Ok((
TimingResult { TimingResult {
time_real, time_real: result.time_real,
time_user, time_user: result.time_user,
time_system, time_system: result.time_system,
}, },
result.status, result.status,
)) ))
@@ -119,7 +134,7 @@ impl<'a> Executor for ShellExecutor<'a> {
for _ in 0..COUNT { for _ in 0..COUNT {
// Just run the shell without any command // Just run the shell without any command
let res = self.time_command(&Command::new(None, ""), None); let res = self.run_command_and_measure(&Command::new(None, ""), None);
match res { match res {
Err(_) => { Err(_) => {
@@ -185,7 +200,7 @@ impl MockExecutor {
} }
impl Executor for MockExecutor { impl Executor for MockExecutor {
fn time_command( fn run_command_and_measure(
&self, &self,
command: &Command<'_>, command: &Command<'_>,
_command_failure_action: Option<CmdFailureAction>, _command_failure_action: Option<CmdFailureAction>,
@@ -204,7 +219,7 @@ impl Executor for MockExecutor {
Ok(( Ok((
TimingResult { TimingResult {
time_real: Self::extract_time(command.get_shell_command()), time_real: Self::extract_time(command.get_command_line()),
time_user: 0.0, time_user: 0.0,
time_system: 0.0, time_system: 0.0,
}, },
+4 -4
View File
@@ -57,7 +57,7 @@ impl<'a> Benchmark<'a> {
error_output: &'static str, error_output: &'static str,
) -> Result<TimingResult> { ) -> Result<TimingResult> {
self.executor self.executor
.time_command(command, Some(CmdFailureAction::RaiseError)) .run_command_and_measure(command, Some(CmdFailureAction::RaiseError))
.map(|r| r.0) .map(|r| r.0)
.map_err(|_| anyhow!(error_output)) .map_err(|_| anyhow!(error_output))
} }
@@ -163,7 +163,7 @@ impl<'a> Benchmark<'a> {
for _ in 0..self.options.warmup_count { for _ in 0..self.options.warmup_count {
let _ = run_preparation_command()?; let _ = run_preparation_command()?;
let _ = self.executor.time_command(self.command, None)?; let _ = self.executor.run_command_and_measure(self.command, None)?;
if let Some(bar) = progress_bar.as_ref() { if let Some(bar) = progress_bar.as_ref() {
bar.inc(1) bar.inc(1)
} }
@@ -189,7 +189,7 @@ impl<'a> Benchmark<'a> {
preparation_result.map_or(0.0, |res| res.time_real + self.executor.time_overhead()); preparation_result.map_or(0.0, |res| res.time_real + self.executor.time_overhead());
// Initial timing run // Initial timing run
let (res, status) = self.executor.time_command(self.command, None)?; let (res, status) = self.executor.run_command_and_measure(self.command, None)?;
let success = status.success(); let success = status.success();
// Determine number of benchmark runs // Determine number of benchmark runs
@@ -239,7 +239,7 @@ impl<'a> Benchmark<'a> {
bar.set_message(msg.to_owned()) bar.set_message(msg.to_owned())
} }
let (res, status) = self.executor.time_command(self.command, None)?; let (res, status) = self.executor.run_command_and_measure(self.command, None)?;
let success = status.success(); let success = status.success();
times_real.push(res.time_real); times_real.push(res.time_real);
+1 -1
View File
@@ -34,7 +34,7 @@ impl<'a> Scheduler<'a> {
pub fn run_benchmarks(&mut self) -> Result<()> { pub fn run_benchmarks(&mut self) -> Result<()> {
let mut executor: Box<dyn Executor> = match self.options.executor_kind { let mut executor: Box<dyn Executor> = match self.options.executor_kind {
ExecutorKind::Mock(ref shell) => Box::new(MockExecutor::new(shell.clone())), ExecutorKind::Mock(ref shell) => Box::new(MockExecutor::new(shell.clone())),
ExecutorKind::Shell(ref shell) => Box::new(ShellExecutor::new(shell, &self.options)), ExecutorKind::Shell(ref shell) => Box::new(ShellExecutor::new(shell, self.options)),
}; };
executor.calibrate()?; executor.calibrate()?;
+12 -12
View File
@@ -55,12 +55,12 @@ impl<'a> Command<'a> {
pub fn get_name(&self) -> String { pub fn get_name(&self) -> String {
self.name.map_or_else( self.name.map_or_else(
|| self.get_shell_command(), || self.get_command_line(),
|name| self.replace_parameters_in(name), |name| self.replace_parameters_in(name),
) )
} }
pub fn get_shell_command(&self) -> String { pub fn get_command_line(&self) -> String {
self.replace_parameters_in(self.expression) self.replace_parameters_in(self.expression)
} }
@@ -82,7 +82,7 @@ impl<'a> Command<'a> {
// //
// hyperfine -L foo 'a,{bar}' -L bar 'baz,quux' 'echo {foo} {bar}' // hyperfine -L foo 'a,{bar}' -L bar 'baz,quux' 'echo {foo} {bar}'
// //
// should not ever run 'echo baz baz'. See `test_get_shell_command_nonoverlapping`. // should not ever run 'echo baz baz'. See `test_get_command_line_nonoverlapping`.
'outer: while let Some(head) = remaining.chars().next() { 'outer: while let Some(head) = remaining.chars().next() {
for (k, v) in &replacements { for (k, v) in &replacements {
if remaining.starts_with(k.as_str()) { if remaining.starts_with(k.as_str()) {
@@ -318,7 +318,7 @@ impl<'a> Commands<'a> {
} }
#[test] #[test]
fn test_get_shell_command_nonoverlapping() { fn test_get_command_line_nonoverlapping() {
let cmd = Command::new_parametrized( let cmd = Command::new_parametrized(
None, None,
"echo {foo} {bar}", "echo {foo} {bar}",
@@ -327,7 +327,7 @@ fn test_get_shell_command_nonoverlapping() {
("bar", ParameterValue::Text("quux".into())), ("bar", ParameterValue::Text("quux".into())),
], ],
); );
assert_eq!(cmd.get_shell_command(), "echo {bar} baz quux"); assert_eq!(cmd.get_command_line(), "echo {bar} baz quux");
} }
#[test] #[test]
@@ -345,7 +345,7 @@ fn test_get_parameterized_command_name() {
impl<'a> fmt::Display for Command<'a> { impl<'a> fmt::Display for Command<'a> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.get_shell_command()) write!(f, "{}", self.get_command_line())
} }
} }
@@ -404,8 +404,8 @@ fn test_build_parameter_list_commands() {
assert_eq!(commands.len(), 2); assert_eq!(commands.len(), 2);
assert_eq!(commands[0].get_name(), "name-1"); assert_eq!(commands[0].get_name(), "name-1");
assert_eq!(commands[1].get_name(), "name-2"); assert_eq!(commands[1].get_name(), "name-2");
assert_eq!(commands[0].get_shell_command(), "echo 1"); assert_eq!(commands[0].get_command_line(), "echo 1");
assert_eq!(commands[1].get_shell_command(), "echo 2"); assert_eq!(commands[1].get_command_line(), "echo 2");
} }
#[test] #[test]
@@ -427,8 +427,8 @@ fn test_build_parameter_scan_commands() {
assert_eq!(commands.len(), 2); assert_eq!(commands.len(), 2);
assert_eq!(commands[0].get_name(), "name-1"); assert_eq!(commands[0].get_name(), "name-1");
assert_eq!(commands[1].get_name(), "name-2"); assert_eq!(commands[1].get_name(), "name-2");
assert_eq!(commands[0].get_shell_command(), "echo 1"); assert_eq!(commands[0].get_command_line(), "echo 1");
assert_eq!(commands[1].get_shell_command(), "echo 2"); assert_eq!(commands[1].get_command_line(), "echo 2");
} }
#[test] #[test]
@@ -444,7 +444,7 @@ fn test_parameter_scan_commands_int() {
.unwrap(); .unwrap();
assert_eq!(commands.len(), 3); assert_eq!(commands.len(), 3);
assert_eq!(commands[2].get_name(), "echo 7"); assert_eq!(commands[2].get_name(), "echo 7");
assert_eq!(commands[2].get_shell_command(), "echo 7"); assert_eq!(commands[2].get_command_line(), "echo 7");
} }
#[test] #[test]
@@ -464,7 +464,7 @@ fn test_parameter_scan_commands_decimal() {
.unwrap(); .unwrap();
assert_eq!(commands.len(), 4); assert_eq!(commands.len(), 4);
assert_eq!(commands[3].get_name(), "echo 0.99"); assert_eq!(commands[3].get_name(), "echo 0.99");
assert_eq!(commands[3].get_shell_command(), "echo 0.99"); assert_eq!(commands[3].get_command_line(), "echo 0.99");
} }
#[test] #[test]
-1
View File
@@ -18,7 +18,6 @@ pub mod options;
pub mod outlier_detection; pub mod outlier_detection;
pub mod output; pub mod output;
pub mod parameter; pub mod parameter;
pub mod shell;
pub mod timer; pub mod timer;
pub mod util; pub mod util;
+16 -7
View File
@@ -1,4 +1,4 @@
use std::process::Command; use std::process::{Command, Stdio};
use std::{cmp, fmt}; use std::{cmp, fmt};
use anyhow::ensure; use anyhow::ensure;
@@ -44,7 +44,7 @@ impl fmt::Display for Shell {
impl Shell { impl Shell {
/// Parse given string as shell command line /// Parse given string as shell command line
pub fn from_str<'a>(s: &str) -> Result<Self, OptionsError<'a>> { pub fn parse_from_str<'a>(s: &str) -> Result<Self, OptionsError<'a>> {
let v = shell_words::split(s).map_err(OptionsError::ShellParseError)?; let v = shell_words::split(s).map_err(OptionsError::ShellParseError)?;
if v.is_empty() || v[0].is_empty() { if v.is_empty() || v[0].is_empty() {
return Err(OptionsError::EmptyShell); return Err(OptionsError::EmptyShell);
@@ -124,6 +124,15 @@ impl Default for CommandOutputPolicy {
} }
} }
impl CommandOutputPolicy {
pub fn get_stdout_stderr(&self) -> (Stdio, Stdio) {
match self {
CommandOutputPolicy::Discard => (Stdio::null(), Stdio::null()),
CommandOutputPolicy::Forward => (Stdio::inherit(), Stdio::inherit()),
}
}
}
pub enum ExecutorKind { pub enum ExecutorKind {
Shell(Shell), Shell(Shell),
Mock(Option<String>), Mock(Option<String>),
@@ -274,7 +283,7 @@ impl Options {
options.executor_kind = match (matches.is_present("debug-mode"), matches.value_of("shell")) options.executor_kind = match (matches.is_present("debug-mode"), matches.value_of("shell"))
{ {
(false, Some(shell)) => ExecutorKind::Shell(Shell::from_str(shell)?), (false, Some(shell)) => ExecutorKind::Shell(Shell::parse_from_str(shell)?),
(false, None) => ExecutorKind::Shell(Shell::default()), (false, None) => ExecutorKind::Shell(Shell::default()),
(true, Some(shell)) => ExecutorKind::Mock(Some(shell.into())), (true, Some(shell)) => ExecutorKind::Mock(Some(shell.into())),
(true, None) => ExecutorKind::Mock(None), (true, None) => ExecutorKind::Mock(None),
@@ -320,7 +329,7 @@ fn test_default_shell() {
#[test] #[test]
fn test_can_parse_shell_command_line_from_str() { fn test_can_parse_shell_command_line_from_str() {
let shell = Shell::from_str("shell -x 'aaa bbb'").unwrap(); let shell = Shell::parse_from_str("shell -x 'aaa bbb'").unwrap();
let s = format!("{}", shell); let s = format!("{}", shell);
assert_eq!(&s, "shell -x 'aaa bbb'"); assert_eq!(&s, "shell -x 'aaa bbb'");
@@ -336,17 +345,17 @@ fn test_can_parse_shell_command_line_from_str() {
// Error cases // Error cases
assert!(matches!( assert!(matches!(
Shell::from_str("shell 'foo").unwrap_err(), Shell::parse_from_str("shell 'foo").unwrap_err(),
OptionsError::ShellParseError(_) OptionsError::ShellParseError(_)
)); ));
assert!(matches!( assert!(matches!(
Shell::from_str("").unwrap_err(), Shell::parse_from_str("").unwrap_err(),
OptionsError::EmptyShell OptionsError::EmptyShell
)); ));
assert!(matches!( assert!(matches!(
Shell::from_str("''").unwrap_err(), Shell::parse_from_str("''").unwrap_err(),
OptionsError::EmptyShell OptionsError::EmptyShell
)); ));
} }
-102
View File
@@ -1,102 +0,0 @@
use std::process::{ExitStatus, Stdio};
use crate::options::Shell;
use crate::timer::get_cpu_timer;
use anyhow::{Context, Result};
/// Used to indicate the result of running a command
#[derive(Debug, Copy, Clone)]
pub struct ExecuteResult {
/// The amount of user time the process used
pub user_time: f64,
/// The amount of cpu time the process used
pub system_time: f64,
/// The exit status of the process
pub status: ExitStatus,
}
/// Execute the given command and return a timing summary
#[cfg(windows)]
pub fn execute_and_time(
stdout: Stdio,
stderr: Stdio,
command: &str,
shell: &Shell,
) -> Result<ExecuteResult> {
let mut child = run_shell_command(stdout, stderr, command, shell)?;
let cpu_timer = get_cpu_timer(&child);
let status = child.wait()?;
let (user_time, system_time) = cpu_timer.stop();
Ok(ExecuteResult {
user_time,
system_time,
status,
})
}
/// Execute the given command and return a timing summary
#[cfg(not(windows))]
pub fn execute_and_time(
stdout: Stdio,
stderr: Stdio,
command: &str,
shell: &Shell,
) -> Result<ExecuteResult> {
let cpu_timer = get_cpu_timer();
let status = run_shell_command(stdout, stderr, command, shell)?;
let (user_time, system_time) = cpu_timer.stop();
Ok(ExecuteResult {
user_time,
system_time,
status,
})
}
/// Run a standard shell command using `sh -c`
#[cfg(not(windows))]
fn run_shell_command(
stdout: Stdio,
stderr: Stdio,
command: &str,
shell: &Shell,
) -> Result<std::process::ExitStatus> {
shell
.command()
.arg("-c")
.arg(command)
.env(
"HYPERFINE_RANDOMIZED_ENVIRONMENT_OFFSET",
"X".repeat(rand::random::<usize>() % 4096usize),
)
.stdin(Stdio::null())
.stdout(stdout)
.stderr(stderr)
.status()
.with_context(|| format!("Failed to run command '{}'", command))
}
/// Run a Windows shell command using `cmd.exe /C`
#[cfg(windows)]
fn run_shell_command(
stdout: Stdio,
stderr: Stdio,
command: &str,
shell: &Shell,
) -> Result<std::process::Child> {
shell
.command()
.arg("/C")
.arg(command)
.stdin(Stdio::null())
.stdout(stdout)
.stderr(stderr)
.spawn()
.with_context(|| format!("Failed to run command '{}'", command))
}
+44 -25
View File
@@ -1,33 +1,20 @@
use std::process::Child; mod wall_clock_timer;
use crate::util::units::Second;
pub mod wallclocktimer;
#[cfg(windows)] #[cfg(windows)]
mod windows_timer; mod windows_timer;
#[cfg(windows)]
pub use self::windows_timer::get_cpu_timer;
#[cfg(not(windows))] #[cfg(not(windows))]
mod unix_timer; mod unix_timer;
#[cfg(not(windows))]
pub use self::unix_timer::get_cpu_timer;
/// Defines start functionality of a timer. use crate::util::units::Second;
pub trait TimerStart { use wall_clock_timer::WallClockTimer;
fn start() -> Self;
fn start_for_process(process: &Child) -> Self;
}
/// Defines stop functionality of a timer. use std::process::{Command, ExitStatus};
pub trait TimerStop {
type Result; use anyhow::Result;
fn stop(&self) -> Self::Result;
}
#[derive(Debug, Copy, Clone)] #[derive(Debug, Copy, Clone)]
pub struct CPUTimes { struct CPUTimes {
/// Total amount of time spent executing in user mode /// Total amount of time spent executing in user mode
pub user_usec: i64, pub user_usec: i64,
@@ -35,11 +22,43 @@ pub struct CPUTimes {
pub system_usec: i64, pub system_usec: i64,
} }
/// Used to indicate the result of running a command
#[derive(Debug, Copy, Clone)] #[derive(Debug, Copy, Clone)]
pub struct CPUInterval { pub struct TimerResult {
/// Total amount of time spent executing in user mode pub time_real: Second,
pub user: Second, pub time_user: Second,
pub time_system: Second,
/// Total amount of time spent executing in kernel mode /// The exit status of the process
pub system: Second, pub status: ExitStatus,
}
/// Execute the given command and return a timing summary
pub fn execute_and_measure(mut command: Command) -> Result<TimerResult> {
let wallclock_timer = WallClockTimer::start();
#[cfg(not(windows))]
let ((time_user, time_system), status) = {
let cpu_timer = self::unix_timer::CPUTimer::start();
let status = command.status()?;
(cpu_timer.stop(), status)
};
#[cfg(windows)]
let ((time_user, time_system), status) = {
let mut child = command.spawn()?;
let cpu_timer = self::windows_timer::CPUTimer::start_for_process(&child);
let status = child.wait()?;
(cpu_timer.stop(), status)
};
let time_real = wallclock_timer.stop();
Ok(TimerResult {
time_real,
time_user,
time_system,
status,
})
} }
+12 -16
View File
@@ -1,35 +1,31 @@
#![cfg(not(windows))] #![cfg(not(windows))]
use std::mem; use std::mem;
use std::process::Child;
use crate::timer::{CPUInterval, CPUTimes, TimerStart, TimerStop}; use crate::timer::CPUTimes;
use crate::util::units::Second; use crate::util::units::Second;
pub fn get_cpu_timer() -> Box<dyn TimerStop<Result = (Second, Second)>> { #[derive(Debug, Copy, Clone)]
Box::new(CPUTimer::start()) pub struct CPUInterval {
/// Total amount of time spent executing in user mode
pub user: Second,
/// Total amount of time spent executing in kernel mode
pub system: Second,
} }
struct CPUTimer { pub struct CPUTimer {
start_cpu: CPUTimes, start_cpu: CPUTimes,
} }
impl TimerStart for CPUTimer { impl CPUTimer {
fn start() -> Self { pub fn start() -> Self {
CPUTimer { CPUTimer {
start_cpu: get_cpu_times(), start_cpu: get_cpu_times(),
} }
} }
fn start_for_process(_: &Child) -> Self { pub fn stop(&self) -> (Second, Second) {
Self::start()
}
}
impl TimerStop for CPUTimer {
type Result = (Second, Second);
fn stop(&self) -> Self::Result {
let end_cpu = get_cpu_times(); let end_cpu = get_cpu_times();
let cpu_interval = cpu_time_interval(&self.start_cpu, &end_cpu); let cpu_interval = cpu_time_interval(&self.start_cpu, &end_cpu);
(cpu_interval.user, cpu_interval.system) (cpu_interval.user, cpu_interval.system)
@@ -1,29 +1,19 @@
use std::process::Child;
use std::time::Instant; use std::time::Instant;
use crate::timer::{TimerStart, TimerStop};
use crate::util::units::Second; use crate::util::units::Second;
pub struct WallClockTimer { pub struct WallClockTimer {
start: Instant, start: Instant,
} }
impl TimerStart for WallClockTimer { impl WallClockTimer {
fn start() -> WallClockTimer { pub fn start() -> WallClockTimer {
WallClockTimer { WallClockTimer {
start: Instant::now(), start: Instant::now(),
} }
} }
fn start_for_process(_: &Child) -> Self { pub fn stop(&self) -> Second {
Self::start()
}
}
impl TimerStop for WallClockTimer {
type Result = Second;
fn stop(&self) -> Second {
let duration = self.start.elapsed(); let duration = self.start.elapsed();
duration.as_secs() as f64 + f64::from(duration.subsec_nanos()) * 1e-9 duration.as_secs() as f64 + f64::from(duration.subsec_nanos()) * 1e-9
} }
+7 -19
View File
@@ -7,35 +7,23 @@ use std::process::Child;
use winapi::um::processthreadsapi::GetProcessTimes; use winapi::um::processthreadsapi::GetProcessTimes;
use winapi::um::winnt::HANDLE; use winapi::um::winnt::HANDLE;
use crate::timer::{CPUTimes, TimerStart, TimerStop}; use crate::timer::CPUTimes;
use crate::util::units::Second; use crate::util::units::Second;
const HUNDRED_NS_PER_MS: i64 = 10; const HUNDRED_NS_PER_MS: i64 = 10;
pub fn get_cpu_timer(process: &Child) -> Box<dyn TimerStop<Result = (Second, Second)>> { pub struct CPUTimer {
Box::new(CPUTimer::start_for_process(process))
}
struct CPUTimer {
handle: RawHandle, handle: RawHandle,
} }
impl TimerStart for CPUTimer { impl CPUTimer {
fn start() -> Self { pub fn start_for_process(process: &Child) -> Self {
panic!()
}
fn start_for_process(process: &Child) -> Self {
CPUTimer { CPUTimer {
handle: process.as_raw_handle(), handle: process.as_raw_handle(),
} }
} }
}
impl TimerStop for CPUTimer { pub fn stop(&self) -> (Second, Second) {
type Result = (Second, Second);
fn stop(&self) -> Self::Result {
let times = get_cpu_times(self.handle); let times = get_cpu_times(self.handle);
( (
times.user_usec as f64 * 1e-6, times.user_usec as f64 * 1e-6,
@@ -44,7 +32,7 @@ impl TimerStop for CPUTimer {
} }
} }
/// Read CPU execution times (dummy for now) /// Read CPU execution times
fn get_cpu_times(handle: RawHandle) -> CPUTimes { fn get_cpu_times(handle: RawHandle) -> CPUTimes {
let (user_usec, system_usec) = unsafe { let (user_usec, system_usec) = unsafe {
let mut _ctime = mem::zeroed(); let mut _ctime = mem::zeroed();
@@ -62,7 +50,7 @@ fn get_cpu_times(handle: RawHandle) -> CPUTimes {
// GetProcessTimes will exit with non-zero if success as per: https://msdn.microsoft.com/en-us/library/windows/desktop/ms683223(v=vs.85).aspx // GetProcessTimes will exit with non-zero if success as per: https://msdn.microsoft.com/en-us/library/windows/desktop/ms683223(v=vs.85).aspx
if res != 0 { if res != 0 {
// Extract times as laid out here: https://support.microsoft.com/en-us/help/188768/info-working-with-the-filetime-structure // Extract times as laid out here: https://support.microsoft.com/en-us/help/188768/info-working-with-the-filetime-structure
// Both user_time and kernel_time are spans that the proces spent in either. // Both user_time and kernel_time are spans that the process spent in either.
let user: i64 = (((user_time.dwHighDateTime as i64) << 32) let user: i64 = (((user_time.dwHighDateTime as i64) << 32)
+ user_time.dwLowDateTime as i64) + user_time.dwLowDateTime as i64)
/ HUNDRED_NS_PER_MS; / HUNDRED_NS_PER_MS;
+1
View File
@@ -1,4 +1,5 @@
pub mod exit_code; pub mod exit_code;
pub mod min_max; pub mod min_max;
pub mod number; pub mod number;
pub mod randomized_environment_offset;
pub mod units; pub mod units;
@@ -0,0 +1,8 @@
/// Returns a string with a random length. This value will be set as an environment
/// variable to account for offset effects. See [1] for more details.
///
/// [1] Mytkowicz, 2009. Producing Wrong Data Without Doing Anything Obviously Wrong!.
/// Sigplan Notices - SIGPLAN. 44. 265-276. 10.1145/1508284.1508275.
pub fn value() -> String {
"X".repeat(rand::random::<usize>() % 4096usize)
}
+12
View File
@@ -147,6 +147,18 @@ fn can_run_failing_commands_with_ignore_failure_option() {
.success(); .success();
} }
#[test]
fn shows_output_of_benchmarked_command() {
hyperfine()
.arg("--runs=2")
.arg("--command-name=dummy")
.arg("--show-output")
.arg("echo 4fd47015")
.assert()
.success()
.stdout(predicate::str::contains("4fd47015").count(2));
}
#[test] #[test]
fn runs_commands_using_user_defined_shell() { fn runs_commands_using_user_defined_shell() {
hyperfine() hyperfine()