Files
hyperfine/src/options.rs
T

524 lines
16 KiB
Rust
Raw Normal View History

2022-05-14 13:21:41 -04:00
use std::fs::File;
use std::io::IsTerminal;
2022-05-14 13:21:41 -04:00
use std::path::PathBuf;
2022-02-22 11:54:00 +01:00
use std::process::{Command, Stdio};
use std::{cmp, env, fmt, io};
2022-02-07 21:03:23 +01:00
use anyhow::ensure;
use clap::ArgMatches;
2021-10-04 22:34:19 +09:00
2022-02-07 21:03:23 +01:00
use crate::command::Commands;
2021-10-04 22:34:19 +09:00
use crate::error::OptionsError;
2022-02-06 20:01:41 +01:00
use crate::util::units::{Second, Unit};
2021-08-22 19:04:22 +02:00
2022-02-07 21:03:23 +01:00
use anyhow::Result;
2021-08-22 19:04:22 +02:00
#[cfg(not(windows))]
pub const DEFAULT_SHELL: &str = "sh";
#[cfg(windows)]
pub const DEFAULT_SHELL: &str = "cmd.exe";
2021-08-22 17:53:08 +02:00
2021-10-04 22:34:19 +09:00
/// Shell to use for executing benchmarked commands
2022-10-22 17:39:05 +02:00
#[derive(Debug, PartialEq)]
2021-10-04 22:34:19 +09:00
pub enum Shell {
/// Default shell command
Default(&'static str),
2022-02-19 19:58:00 +01:00
2021-10-04 22:34:19 +09:00
/// Custom shell command specified via --shell
Custom(Vec<String>),
}
impl Default for Shell {
fn default() -> Self {
Shell::Default(DEFAULT_SHELL)
}
}
impl fmt::Display for Shell {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
2024-05-31 13:26:35 -07:00
Shell::Default(cmd) => write!(f, "{cmd}"),
2021-10-04 22:49:37 +09:00
Shell::Custom(cmdline) => write!(f, "{}", shell_words::join(cmdline)),
2021-10-04 22:34:19 +09:00
}
}
}
impl Shell {
/// Parse given string as shell command line
2022-02-22 10:13:06 +01:00
pub fn parse_from_str<'a>(s: &str) -> Result<Self, OptionsError<'a>> {
2021-10-04 23:07:38 +09:00
let v = shell_words::split(s).map_err(OptionsError::ShellParseError)?;
2021-10-04 22:49:37 +09:00
if v.is_empty() || v[0].is_empty() {
2021-10-04 22:34:19 +09:00
return Err(OptionsError::EmptyShell);
}
Ok(Shell::Custom(v))
}
pub fn command(&self) -> Command {
match self {
Shell::Default(cmd) => Command::new(cmd),
Shell::Custom(cmdline) => {
let mut c = Command::new(&cmdline[0]);
c.args(&cmdline[1..]);
c
}
}
}
}
2021-08-22 17:53:08 +02:00
/// Action to take when an executed command fails.
2022-09-07 09:20:50 +02:00
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2021-08-22 17:53:08 +02:00
pub enum CmdFailureAction {
/// Exit with an error message
RaiseError,
/// Simply ignore the non-zero exit code
Ignore,
}
/// Output style type option
2022-09-07 09:20:50 +02:00
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2021-08-22 17:53:08 +02:00
pub enum OutputStyleOption {
/// Do not output with colors or any special formatting
Basic,
/// Output with full color and formatting
Full,
/// Keep elements such as progress bar, but use no coloring
NoColor,
/// Keep coloring, but use no progress bar
Color,
/// Disable all the output
Disabled,
}
2023-06-03 21:06:50 +02:00
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SortOrder {
Command,
MeanTime,
}
2022-02-19 20:01:49 +01:00
/// Bounds for the number of benchmark runs
pub struct RunBounds {
2021-08-22 17:53:08 +02:00
/// Minimum number of benchmark runs
pub min: u64,
/// Maximum number of benchmark runs
pub max: Option<u64>,
}
2022-02-19 20:01:49 +01:00
impl Default for RunBounds {
2022-02-20 13:15:54 +01:00
fn default() -> Self {
2022-02-19 20:01:49 +01:00
RunBounds { min: 10, max: None }
2021-08-22 17:53:08 +02:00
}
}
2023-03-15 10:08:20 +01:00
#[derive(Debug, Default, Clone, PartialEq)]
2022-09-11 16:20:22 -05:00
pub enum CommandInputPolicy {
2022-10-15 14:29:54 -05:00
/// Read from the null device
2023-03-15 10:08:20 +01:00
#[default]
2022-09-11 16:20:22 -05:00
Null,
2022-10-15 14:29:54 -05:00
/// Read input from a file
2022-09-11 16:20:22 -05:00
File(PathBuf),
}
impl CommandInputPolicy {
pub fn get_stdin(&self) -> io::Result<Stdio> {
let stream: Stdio = match self {
CommandInputPolicy::Null => Stdio::null(),
CommandInputPolicy::File(path) => {
2023-03-15 09:49:43 +01:00
let file: File = File::open(path)?;
2022-09-11 16:20:22 -05:00
Stdio::from(file)
}
};
Ok(stream)
}
}
2022-02-20 13:15:54 +01:00
/// How to handle the output of benchmarked commands
2023-03-15 10:08:20 +01:00
#[derive(Debug, Clone, PartialEq, Eq, Default)]
2022-02-20 13:15:54 +01:00
pub enum CommandOutputPolicy {
2022-05-17 14:21:16 -04:00
/// Redirect output to the null device
2023-03-15 10:08:20 +01:00
#[default]
2022-05-17 14:21:16 -04:00
Null,
2021-08-22 17:53:08 +02:00
2022-05-14 13:21:41 -04:00
/// Feed output through a pipe before discarding it
Pipe,
/// Redirect output to a file
File(PathBuf),
2022-02-20 13:15:54 +01:00
/// Show command output on the terminal
2022-05-17 14:21:16 -04:00
Inherit,
2022-02-20 13:15:54 +01:00
}
2022-02-22 11:54:00 +01:00
impl CommandOutputPolicy {
2022-05-14 13:21:41 -04:00
pub fn get_stdout_stderr(&self) -> io::Result<(Stdio, Stdio)> {
let streams = match self {
2022-05-17 14:21:16 -04:00
CommandOutputPolicy::Null => (Stdio::null(), Stdio::null()),
2022-05-14 13:21:41 -04:00
// Typically only stdout is performance-relevant, so just pipe that
CommandOutputPolicy::Pipe => (Stdio::piped(), Stdio::null()),
CommandOutputPolicy::File(path) => {
2023-03-15 09:49:43 +01:00
let file = File::create(path)?;
2022-05-14 13:21:41 -04:00
(file.into(), Stdio::null())
}
2022-05-17 14:21:16 -04:00
CommandOutputPolicy::Inherit => (Stdio::inherit(), Stdio::inherit()),
2022-05-14 13:21:41 -04:00
};
Ok(streams)
2022-02-22 11:54:00 +01:00
}
}
2022-02-22 08:36:56 +01:00
pub enum ExecutorKind {
Raw,
2022-02-22 08:36:56 +01:00
Shell(Shell),
2022-02-22 08:58:57 +01:00
Mock(Option<String>),
2022-02-22 08:36:56 +01:00
}
impl Default for ExecutorKind {
fn default() -> Self {
ExecutorKind::Shell(Shell::default())
}
}
2022-02-20 13:15:54 +01:00
/// The main settings for a hyperfine benchmark session
pub struct Options {
2022-02-19 20:01:49 +01:00
/// Upper and lower bound for the number of benchmark runs
pub run_bounds: RunBounds,
2021-08-22 17:53:08 +02:00
2022-02-20 13:15:54 +01:00
/// Number of warmup runs
pub warmup_count: u64,
2021-08-22 17:53:08 +02:00
/// Minimum benchmarking time
2022-02-20 13:15:54 +01:00
pub min_benchmarking_time: Second,
2021-08-22 17:53:08 +02:00
/// Whether or not to ignore non-zero exit codes
2022-02-20 13:15:54 +01:00
pub command_failure_action: CmdFailureAction,
// Command to use as a reference for relative speed comparison
pub reference_command: Option<String>,
2022-02-20 13:19:23 +01:00
/// Command(s) to run before each timing run
2021-08-22 17:53:08 +02:00
pub preparation_command: Option<Vec<String>>,
2024-01-21 19:27:08 +00:00
/// Command(s) to run after each timing run
pub conclusion_command: Option<Vec<String>>,
2022-02-20 13:15:54 +01:00
/// Command to run before each *batch* of timing runs, i.e. before each individual benchmark
pub setup_command: Option<String>,
/// Command to run after each *batch* of timing runs, i.e. after each individual benchmark
2021-08-22 17:53:08 +02:00
pub cleanup_command: Option<String>,
2022-02-20 13:15:54 +01:00
/// What color mode to use for the terminal output
2021-08-22 17:53:08 +02:00
pub output_style: OutputStyleOption,
2023-06-03 21:06:50 +02:00
/// How to order benchmarks in the relative speed comparison
pub sort_order_speed_comparison: SortOrder,
/// How to order benchmarks in the markup format exports
pub sort_order_exports: SortOrder,
2022-02-22 08:36:56 +01:00
/// Determines how we run commands
pub executor_kind: ExecutorKind,
2021-08-22 17:53:08 +02:00
/// Where input to the benchmarked command comes from
pub command_input_policy: CommandInputPolicy,
2024-11-11 22:18:19 +01:00
/// What to do with the output of the benchmarked commands
pub command_output_policies: Vec<CommandOutputPolicy>,
2021-08-22 17:53:08 +02:00
2022-09-11 16:20:22 -05:00
/// Which time unit to use when displaying results
2021-08-22 17:53:08 +02:00
pub time_unit: Option<Unit>,
}
2022-02-06 18:20:38 +01:00
impl Default for Options {
fn default() -> Options {
Options {
2022-02-19 20:01:49 +01:00
run_bounds: RunBounds::default(),
2022-02-20 13:23:54 +01:00
warmup_count: 0,
2022-02-20 13:15:54 +01:00
min_benchmarking_time: 3.0,
command_failure_action: CmdFailureAction::RaiseError,
reference_command: None,
2021-08-22 17:53:08 +02:00
preparation_command: None,
2024-01-21 19:27:08 +00:00
conclusion_command: None,
2022-02-20 13:23:54 +01:00
setup_command: None,
2021-08-22 17:53:08 +02:00
cleanup_command: None,
output_style: OutputStyleOption::Full,
2023-06-03 21:06:50 +02:00
sort_order_speed_comparison: SortOrder::MeanTime,
sort_order_exports: SortOrder::Command,
2022-02-22 08:36:56 +01:00
executor_kind: ExecutorKind::default(),
2024-11-11 22:18:19 +01:00
command_output_policies: vec![CommandOutputPolicy::Null],
2021-08-22 17:53:08 +02:00
time_unit: None,
2022-09-11 16:20:22 -05:00
command_input_policy: CommandInputPolicy::Null,
2021-08-22 17:53:08 +02:00
}
}
}
2021-10-04 22:49:37 +09:00
2022-02-06 18:20:38 +01:00
impl Options {
pub fn from_cli_arguments<'a>(matches: &ArgMatches) -> Result<Self, OptionsError<'a>> {
let mut options = Self::default();
let param_to_u64 = |param| {
matches
2022-10-27 20:42:33 +02:00
.get_one::<String>(param)
.map(|n| {
n.parse::<u64>()
.map_err(|e| OptionsError::IntParsingError(param, e))
})
.transpose()
};
options.warmup_count = param_to_u64("warmup")?.unwrap_or(options.warmup_count);
let mut min_runs = param_to_u64("min-runs")?;
let mut max_runs = param_to_u64("max-runs")?;
if let Some(runs) = param_to_u64("runs")? {
min_runs = Some(runs);
max_runs = Some(runs);
}
match (min_runs, max_runs) {
(Some(min), None) => {
2022-02-19 20:01:49 +01:00
options.run_bounds.min = min;
}
(None, Some(max)) => {
// Since the minimum was not explicit we lower it if max is below the default min.
2022-02-19 20:01:49 +01:00
options.run_bounds.min = cmp::min(options.run_bounds.min, max);
options.run_bounds.max = Some(max);
}
(Some(min), Some(max)) if min > max => {
return Err(OptionsError::EmptyRunsRange);
}
(Some(min), Some(max)) => {
2022-02-19 20:01:49 +01:00
options.run_bounds.min = min;
options.run_bounds.max = Some(max);
}
(None, None) => {}
};
2022-10-27 20:42:33 +02:00
options.setup_command = matches.get_one::<String>("setup").map(String::from);
options.reference_command = matches.get_one::<String>("reference").map(String::from);
options.preparation_command = matches
2022-10-27 20:42:33 +02:00
.get_many::<String>("prepare")
.map(|values| values.map(String::from).collect::<Vec<String>>());
2024-01-21 19:27:08 +00:00
options.conclusion_command = matches
.get_many::<String>("conclude")
.map(|values| values.map(String::from).collect::<Vec<String>>());
2022-10-27 20:42:33 +02:00
options.cleanup_command = matches.get_one::<String>("cleanup").map(String::from);
2024-11-11 22:18:19 +01:00
options.command_output_policies = if matches.get_flag("show-output") {
vec![CommandOutputPolicy::Inherit]
} else if let Some(output_values) = matches.get_many::<String>("output") {
let mut policies = vec![];
for value in output_values {
let policy = match value.as_str() {
"null" => CommandOutputPolicy::Null,
"pipe" => CommandOutputPolicy::Pipe,
"inherit" => CommandOutputPolicy::Inherit,
arg => {
let path = PathBuf::from(arg);
if path.components().count() <= 1 {
return Err(OptionsError::UnknownOutputPolicy(arg.to_string()));
}
CommandOutputPolicy::File(path)
}
2024-11-11 22:18:19 +01:00
};
policies.push(policy);
2022-05-14 13:21:41 -04:00
}
2024-11-11 22:18:19 +01:00
policies
2022-02-20 13:15:54 +01:00
} else {
2024-11-11 22:18:19 +01:00
vec![CommandOutputPolicy::Null]
2022-02-20 13:15:54 +01:00
};
2022-10-27 20:42:33 +02:00
options.output_style = match matches.get_one::<String>("style").map(|s| s.as_str()) {
Some("full") => OutputStyleOption::Full,
Some("basic") => OutputStyleOption::Basic,
Some("nocolor") => OutputStyleOption::NoColor,
Some("color") => OutputStyleOption::Color,
Some("none") => OutputStyleOption::Disabled,
_ => {
2024-11-11 22:18:19 +01:00
if options
.command_output_policies
.iter()
.any(|policy| *policy == CommandOutputPolicy::Inherit)
|| !io::stdout().is_terminal()
2022-02-20 13:15:54 +01:00
{
OutputStyleOption::Basic
2022-09-07 08:44:57 +02:00
} else if env::var_os("TERM")
.map(|t| t == "unknown" || t == "dumb")
2022-10-24 17:34:37 +02:00
.unwrap_or(!cfg!(target_os = "windows"))
2022-09-07 08:44:57 +02:00
|| env::var_os("NO_COLOR")
.map(|t| !t.is_empty())
.unwrap_or(false)
{
OutputStyleOption::NoColor
2022-05-17 14:21:16 -04:00
} else {
OutputStyleOption::Full
}
}
};
match options.output_style {
OutputStyleOption::Basic | OutputStyleOption::NoColor => {
colored::control::set_override(false)
}
OutputStyleOption::Full | OutputStyleOption::Color => {
colored::control::set_override(true)
}
OutputStyleOption::Disabled => {}
};
2023-06-03 21:06:50 +02:00
(
options.sort_order_speed_comparison,
options.sort_order_exports,
) = match matches.get_one::<String>("sort").map(|s| s.as_str()) {
None | Some("auto") => (SortOrder::MeanTime, SortOrder::Command),
Some("command") => (SortOrder::Command, SortOrder::Command),
Some("mean-time") => (SortOrder::MeanTime, SortOrder::MeanTime),
Some(_) => unreachable!("Unknown sort order"),
};
2022-10-27 22:09:41 +02:00
options.executor_kind = if matches.get_flag("no-shell") {
ExecutorKind::Raw
} else {
2022-10-28 11:23:03 +02:00
match (
matches.get_flag("debug-mode"),
matches.get_one::<String>("shell"),
) {
(false, Some(shell)) if shell == "default" => ExecutorKind::Shell(Shell::default()),
(false, Some(shell)) if shell == "none" => ExecutorKind::Raw,
(false, Some(shell)) => ExecutorKind::Shell(Shell::parse_from_str(shell)?),
(false, None) => ExecutorKind::Shell(Shell::default()),
(true, Some(shell)) => ExecutorKind::Mock(Some(shell.into())),
(true, None) => ExecutorKind::Mock(None),
}
2022-02-22 08:36:56 +01:00
};
2022-10-27 22:09:41 +02:00
if matches.get_flag("ignore-failure") {
2022-02-20 13:15:54 +01:00
options.command_failure_action = CmdFailureAction::Ignore;
}
2022-10-27 20:42:33 +02:00
options.time_unit = match matches.get_one::<String>("time-unit").map(|s| s.as_str()) {
2023-10-05 09:39:00 +02:00
Some("microsecond") => Some(Unit::MicroSecond),
Some("millisecond") => Some(Unit::MilliSecond),
Some("second") => Some(Unit::Second),
_ => None,
};
2022-10-27 20:42:33 +02:00
if let Some(time) = matches.get_one::<String>("min-benchmarking-time") {
options.min_benchmarking_time = time
.parse::<f64>()
.map_err(|e| OptionsError::FloatParsingError("min-benchmarking-time", e))?;
}
2023-03-15 09:23:20 +01:00
options.command_input_policy = if let Some(path_str) = matches.get_one::<String>("input") {
2023-03-21 20:55:03 +01:00
if path_str == "null" {
CommandInputPolicy::Null
} else {
let path = PathBuf::from(path_str);
if !path.exists() {
return Err(OptionsError::StdinDataFileDoesNotExist(
path_str.to_string(),
));
}
CommandInputPolicy::File(path)
2022-09-11 16:20:22 -05:00
}
} else {
CommandInputPolicy::Null
};
Ok(options)
}
2022-02-07 21:03:23 +01:00
2024-11-11 22:18:19 +01:00
pub fn validate_against_command_list(&mut self, commands: &Commands) -> Result<()> {
let has_reference_command = self.reference_command.is_some();
let num_commands = commands.num_commands(has_reference_command);
2022-02-07 21:03:23 +01:00
if let Some(preparation_command) = &self.preparation_command {
ensure!(
preparation_command.len() <= 1 || num_commands == preparation_command.len(),
2024-11-11 22:18:19 +01:00
"The '--prepare' option has to be provided just once or N times, where N={num_commands} is the \
number of benchmark commands (including a potential reference)."
2022-02-07 21:03:23 +01:00
);
}
2024-01-21 19:27:08 +00:00
if let Some(conclusion_command) = &self.conclusion_command {
ensure!(
conclusion_command.len() <= 1 || num_commands == conclusion_command.len(),
2024-11-11 22:18:19 +01:00
"The '--conclude' option has to be provided just once or N times, where N={num_commands} is the \
number of benchmark commands (including a potential reference)."
);
}
if self.command_output_policies.len() == 1 {
self.command_output_policies =
vec![self.command_output_policies[0].clone(); num_commands];
} else {
ensure!(
self.command_output_policies.len() == num_commands,
"The '--output' option has to be provided just once or N times, where N={num_commands} is the \
number of benchmark commands (including a potential reference)."
2024-01-21 19:27:08 +00:00
);
}
2022-02-07 21:03:23 +01:00
Ok(())
}
}
2021-10-04 22:49:37 +09:00
#[test]
2022-02-20 13:31:49 +01:00
fn test_default_shell() {
2021-10-04 22:49:37 +09:00
let shell = Shell::default();
2024-05-31 13:26:35 -07:00
let s = format!("{shell}");
2021-10-04 22:49:37 +09:00
assert_eq!(&s, DEFAULT_SHELL);
let cmd = shell.command();
2022-02-20 13:25:50 +01:00
assert_eq!(cmd.get_program(), DEFAULT_SHELL);
2021-10-04 22:49:37 +09:00
}
#[test]
2022-02-20 13:19:23 +01:00
fn test_can_parse_shell_command_line_from_str() {
2022-02-22 10:13:06 +01:00
let shell = Shell::parse_from_str("shell -x 'aaa bbb'").unwrap();
2021-10-04 22:49:37 +09:00
2024-05-31 13:26:35 -07:00
let s = format!("{shell}");
2021-10-04 22:49:37 +09:00
assert_eq!(&s, "shell -x 'aaa bbb'");
let cmd = shell.command();
2022-02-05 22:14:06 +01:00
assert_eq!(cmd.get_program().to_string_lossy(), "shell");
assert_eq!(
cmd.get_args()
.map(|a| a.to_string_lossy())
.collect::<Vec<_>>(),
vec!["-x", "aaa bbb"]
);
2021-10-04 22:49:37 +09:00
// Error cases
2022-02-05 22:14:06 +01:00
assert!(matches!(
2022-02-22 10:13:06 +01:00
Shell::parse_from_str("shell 'foo").unwrap_err(),
2022-02-05 22:14:06 +01:00
OptionsError::ShellParseError(_)
));
2021-10-04 22:49:37 +09:00
2022-02-06 17:56:59 +01:00
assert!(matches!(
2022-02-22 10:13:06 +01:00
Shell::parse_from_str("").unwrap_err(),
2022-02-06 17:56:59 +01:00
OptionsError::EmptyShell
));
2021-10-04 22:49:37 +09:00
2022-02-06 17:56:59 +01:00
assert!(matches!(
2022-02-22 10:13:06 +01:00
Shell::parse_from_str("''").unwrap_err(),
2022-02-06 17:56:59 +01:00
OptionsError::EmptyShell
));
2021-10-04 22:49:37 +09:00
}