Skip to content
Myr

Add --env for benchmark environment overrides

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

authored by David Peter · committed by David Peter · parent 067ee70 · Browse files · 12 files+292 added−15 removed
This commit

State

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

Diff stats

12 files+292 added−15 removed

  • tests:+60 added−0 removed
  • other:+232 added−15 removed

12 files+292 added−15 removed

modified:doc/hyperfine.1+11 added
190 unmodified lines
191.IP192The option can be specified multiple times to run benchmarks for all193possible parameter combinations.194.HP195\fB\-\-env\fR \fIASSIGNMENTS\fP196.IP197Set environment variables for benchmark commands and their respective setup, prepare, conclude,198and cleanup commands. Assignments are space-separated and support shell-style quoting,199but no shell expansion, e.g. \fB\-\-env\fR 'OMP_NUM_THREADS=8 CFLAGS="\-O3 \-march=native"'.200Specify once for all commands or once per benchmark command, like \fB\-\-prepare\fR.201Use an empty string for no overrides. Values can contain parameter placeholders.202.IP203For example, \fBhyperfine \-P threads 1 8 \-\-env\fR 'OMP_NUM_THREADS={threads}' 'my_command'204benchmarks 'my_command' with OMP_NUM_THREADS ranging from 1 to 8.205.HP206\fB\-\-shell\fR \fISHELL\fP207.IP208Set the shell to use for executing benchmarked commands, including warmup runs209(default: none). This can be the name or the path to the shell executable,
196 unmodified lines
modified:src/benchmark/benchmark_result.rs+8 added-6 removed
16 unmodified lines
17 /// For example, `sleep {duration}` with `duration=1` becomes `sleep 1`,18 /// regardless of any custom name.19 pub command: String,2021 /// The custom name after parameter substitution, if it differs from `command`.22 /// For example, `--command-name="wait {duration}s"` with `duration=1`23 /// produces `Some("wait 1s")`. Without a custom name, or when the expanded24 /// name equals `command`, this is `None`.21 /// The custom or automatically generated name after parameter substitution,22 /// if it differs from `command`. Automatic names include environment overrides.23 #[serde(skip_serializing_if = "Option::is_none")]24 pub name: Option<String>,2528 /// The custom name (or `command`), followed by parameters not used in the29 /// command template, in command-line order. For example, `sleep {duration}`26 /// The name, followed by parameters not used in the command or environment27 /// templates, in command-line order. For example, `sleep {duration}`28 /// with `duration=1`, `branch=main`, and the custom name `wait {duration}s`29 /// produces `wait 1s (branch = main)`. Without the custom name, this is30 /// `sleep 1 (branch = main)`. Used in summaries and table exports.31 #[serde(skip_serializing)]
5 unmodified lines
3738 /// Parameter values for this benchmark39 #[serde(skip_serializing_if = "BTreeMap::is_empty")]40 pub parameters: BTreeMap<String, Parameter>,4142 /// Explicit environment overrides after parameter substitution.43 #[serde(skip_serializing_if = "BTreeMap::is_empty")]44 pub environment: BTreeMap<String, String>,45}4647impl BenchmarkResult {48 pub fn get_name(&self) -> &str {
3 unmodified lines
modified:src/benchmark/executor.rs+1 added
213 unmodified lines
214 output_policy: &CommandOutputPolicy,215 ) -> Result<Measurement> {216 let on_windows_cmd = cfg!(windows) && *self.shell == Shell::Default("cmd.exe");217 let mut command_builder = self.shell.command();218 command_builder.envs(command.get_environment());219 command_builder.arg(if on_windows_cmd { "/C" } else { "-c" });220221 // Windows needs special treatment for its behavior on parsing cmd arguments222 if on_windows_cmd {
179 unmodified lines
modified:src/benchmark/mod.rs+7 added-1 removed
59 unmodified lines
60 kind: &'static str,61 output_policy: &CommandOutputPolicy,62 iteration: executor::BenchmarkIteration,63 ) -> Result<Measurement> {64 let command = command.clone().with_environment_from(self.command);65 self.executor65 .run_intermediate_command_and_measure(command, iteration, output_policy)66 .run_intermediate_command_and_measure(&command, iteration, output_policy)67 .map_err(|error| {68 let hint = if cfg!(windows) {69 "Append ' || exit /b 0' to the command if this failure can be ignored."70 } else {
372 unmodified lines
443444 Ok(BenchmarkResult {445 command,446 name,447 environment: self448 .command449 .get_environment()450 .map(|(name, value)| (name.to_owned(), value))451 .collect(),452 display_name: self.command.get_name_with_unused_parameters(),453 measurements,454 parameters: self455 .command
14 unmodified lines
modified:src/export/csv.rs+2 added
89 unmodified lines
90 let exporter = CsvExporter::default();9192 let results = vec![93 BenchmarkResult {94 environment: BTreeMap::new(),95 command: String::from("echo command_a"),96 name: Some(String::from("command_a")),97 display_name: String::from("command_a"),98 measurements: Measurements::new(vec![
42 unmodified lines
141 params142 },143 },144 BenchmarkResult {145 environment: BTreeMap::new(),146 command: String::from("command_b"),147 name: None,148 display_name: String::from("command_b"),149 measurements: Measurements::new(vec![
76 unmodified lines
modified:src/export/tests.rs+8 added
33 unmodified lines
34#[test]35fn test_markup_export_auto_ms() {36 let results = [37 BenchmarkResult {38 environment: BTreeMap::new(),39 command: String::from("sleep 0.1"),40 name: None,41 display_name: String::from("sleep 0.1"),42 measurements: Measurements::new(vec![
27 unmodified lines
70 ]),71 parameters: BTreeMap::new(),72 },73 BenchmarkResult {74 environment: BTreeMap::new(),75 command: String::from("sleep 2"),76 name: None,77 display_name: String::from("sleep 2"),78 measurements: Measurements::new(vec![
69 unmodified lines
148#[test]149fn test_markup_export_auto_s() {150 let results = [151 BenchmarkResult {152 environment: BTreeMap::new(),153 command: String::from("sleep 2"),154 name: None,155 display_name: String::from("sleep 2"),156 measurements: Measurements::new(vec![
27 unmodified lines
184 ]),185 parameters: BTreeMap::new(),186 },187 BenchmarkResult {188 environment: BTreeMap::new(),189 command: String::from("sleep 0.1"),190 name: None,191 display_name: String::from("sleep 0.1"),192 measurements: Measurements::new(vec![
69 unmodified lines
262#[test]263fn test_markup_export_manual_ms() {264 let timing_results = [265 BenchmarkResult {266 environment: BTreeMap::new(),267 command: String::from("sleep 2"),268 name: None,269 display_name: String::from("sleep 2"),270 measurements: Measurements::new(vec![
27 unmodified lines
298 ]),299 parameters: BTreeMap::new(),300 },301 BenchmarkResult {302 environment: BTreeMap::new(),303 command: String::from("sleep 0.1"),304 name: None,305 display_name: String::from("sleep 0.1"),306 measurements: Measurements::new(vec![
68 unmodified lines
375#[test]376fn test_markup_export_manual_s() {377 let results = [378 BenchmarkResult {379 environment: BTreeMap::new(),380 command: String::from("sleep 2"),381 name: None,382 display_name: String::from("sleep 2"),383 measurements: Measurements::new(vec![
27 unmodified lines
411 ]),412 parameters: BTreeMap::new(),413 },414 BenchmarkResult {415 environment: BTreeMap::new(),416 command: String::from("sleep 0.1"),417 name: None,418 display_name: String::from("sleep 0.1"),419 measurements: Measurements::new(vec![
59 unmodified lines
modified:src/cli.rs+22 added
118 unmodified lines
119 .help("Perform exactly NUM runs for each command. If this option is not specified, \120 hyperfine automatically determines the number of runs."),121 )122 .arg(123 Arg::new("env")124 .long("env")125 .action(ArgAction::Append)126 .num_args(1)127 .value_name("ASSIGNMENTS")128 .help("Set environment variables for benchmark commands and their respective setup, \129 prepare, conclude, and cleanup commands. Assignments are space-separated and \130 support shell-style quoting, but no shell expansion:\n\n \131 hyperfine \\\n \132 --env 'OMP_NUM_THREADS=8 CFLAGS=\"-O3 -march=native\"' \\\n \133 'my_command'\n\n\134 Specify once for all commands or once per benchmark command:\n\n \135 hyperfine \\\n \136 --env 'OMP_NUM_THREADS=8' './benchmark-cpp' \\\n \137 --env 'RAYON_NUM_THREADS=8' './benchmark-rust'\n\n\138 Use an empty --env='' for no overrides. Values can contain parameter placeholders. \139 For example, the following benchmarks 'my_command' with OMP_NUM_THREADS ranging \140 from 1 to 8:\n\n \141 hyperfine -P threads 1 8 \\\n \142 --env 'OMP_NUM_THREADS={threads}' 'my_command'"),143 )144 .arg(145 Arg::new("setup")146 .long("setup")147 .short('s')148 .action(ArgAction::Set)
298 unmodified lines
modified:src/command.rs+91 added-6 removed
12 unmodified lines
13};1415use clap::{parser::ValuesRef, ArgMatches};1617use anyhow::{bail, Context, Result};17use anyhow::{bail, ensure, Context, Result};18use rust_decimal::Decimal;1920type Environment = Vec<(String, String)>;2122/// A command that should be benchmarked.23#[derive(Debug, Clone, PartialEq, Eq)]24pub struct Command<'a> {25 /// The command name (without parameter substitution)
3 unmodified lines
29 expression: &'a str,3031 /// Zero or more parameter values.32 parameters: Vec<ParameterNameAndValue<'a>>,3334 /// Environment overrides, before parameter substitution.35 environment: Environment,36}3738impl<'a> Command<'a> {39 pub fn new(name: Option<&'a str>, expression: &'a str) -> Command<'a> {40 Command {41 name,42 expression,43 parameters: Vec::new(),44 environment: Vec::new(),45 }46 }4748 pub fn new_parametrized(
4 unmodified lines
53 Command {54 name,55 expression,56 parameters: parameters.into_iter().collect(),57 environment: Vec::new(),58 }59 }6061 pub fn get_name(&self) -> String {55 self.name.map_or_else(56 || self.get_command_line(),57 |name| self.replace_parameters_in(name),58 )62 match self.name {63 Some(name) => self.replace_parameters_in(name),64 None => {65 let environment = self66 .get_environment()67 .map(|(name, value)| format!("{name}={}", shell_words::quote(&value)))68 .collect::<Vec<_>>()69 .join(" ");70 if environment.is_empty() {71 self.get_command_line()72 } else {73 format!("{environment} {}", self.get_command_line())74 }75 }76 }77 }7879 pub fn get_name_with_unused_parameters(&self) -> String {80 let parameters = self
23 unmodified lines
104105 if let Some(program_name) = tokens.next() {106 let mut command_builder = std::process::Command::new(program_name);107 command_builder.args(tokens);108 command_builder.envs(self.get_environment());109 Ok(command_builder)110 } else {111 bail!("Can not execute empty command")112 }
2 unmodified lines
115 pub fn get_parameters(&self) -> &[(&'a str, ParameterValue)] {116 &self.parameters117 }118119 pub fn get_environment(&self) -> impl Iterator<Item = (&str, String)> {120 self.environment121 .iter()122 .map(move |(name, value)| (name.as_str(), self.replace_parameters_in(value)))123 }124125 pub fn with_environment_from(mut self, command: &Command<'_>) -> Self {126 self.environment = command.environment.clone();127 self128 }129130 pub fn is_parameter_unused(&self, parameter: &str) -> bool {131 let placeholder = format!("{{{parameter}}}");101 !self.expression.contains(&format!("{{{parameter}}}"))132 !self.expression.contains(&placeholder)133 && !self134 .environment135 .iter()136 .any(|(_, value)| value.contains(&placeholder))137 }138139 pub fn get_unused_parameters(&self) -> impl Iterator<Item = &(&'a str, ParameterValue)> {140 self.parameters
30 unmodified lines
171172/// A collection of commands that should be benchmarked173pub struct Commands<'a>(Vec<Command<'a>>);174175fn parse_environment(value: &str) -> Result<Environment> {176 let mut environment = Environment::new();177 for assignment in shell_words::split(value).context("Failed to parse '--env' assignments")? {178 let (name, value) = assignment.split_once('=').with_context(|| {179 format!(180 "Invalid value '{assignment}' for '--env': expected an assignment like NAME=value or NAME=\"quoted value\"."181 )182 })?;183 ensure!(184 !name.is_empty()185 && name.bytes().enumerate().all(|(index, byte)| {186 byte == b'_'187 || byte.is_ascii_alphabetic()188 || (index > 0 && byte.is_ascii_digit())189 }),190 "Invalid environment variable name '{name}' in '--env'"191 );192 // Keep only the last assignment, including case variants on Windows.193 environment.retain(|(key, _)| {194 if cfg!(windows) {195 !key.eq_ignore_ascii_case(name)196 } else {197 key != name198 }199 });200 environment.push((name.to_owned(), value.to_owned()));201 }202 Ok(environment)203}204205impl<'a> Commands<'a> {206 pub fn from_cli_arguments(matches: &'a ArgMatches) -> Result<Commands<'a>> {207 let mut commands = Self::build_from_cli_arguments(matches)?;208 if let Some(values) = matches.get_many::<String>("env") {209 let environments = values210 .map(|value| parse_environment(value))211 .collect::<Result<Vec<_>>>()?;212 let num_commands = commands.num_commands();213 ensure!(214 environments.len() == 1 || environments.len() == num_commands,215 "The '--env' option has to be provided just once or N times, where N={num_commands} is the \216 number of benchmark commands."217 );218 for (index, command) in commands.0.iter_mut().enumerate() {219 command.environment =220 environments[if environments.len() == 1 { 0 } else { index }].clone();221 }222 }223 Ok(commands)224 }225226 fn build_from_cli_arguments(matches: &'a ArgMatches) -> Result<Commands<'a>> {227 let command_names = matches.get_many::<String>("command-name");228 let command_strings = matches229 .get_many::<String>("command")230 .unwrap_or_default()
458 unmodified lines
modified:src/main.rs+8 added
45 unmodified lines
46 && cli_arguments.get_one::<String>("shell").is_none()47 {48 for command in commands.iter() {49 let command_line = command.get_command_line();50 if shell_syntax::starts_with_assignment(&command_line) {51 bail!(52 "Cannot run '{command_line}' directly because it starts with a variable assignment.\n\53 Use the --env option to set environment variables, for example:\n\n \54 hyperfine --env 'OMP_NUM_THREADS=8 CFLAGS=\"-O3 -march=native\"' 'my_command'\n\n\55 Alternatively, use -S / --shell=default to run the command in a shell."56 );57 }58 if let Some(operator) = shell_syntax::first_unquoted_operator(&command_line) {59 bail!(60 concat!(61 "Command '{command_line}' contains unquoted shell syntax ('{operator}').\n",
41 unmodified lines
modified:src/shell_syntax.rs+49 added-2 removed
1//! Conservative detection of shell operators in commands run without a shell.1//! Conservative detection of shell syntax in commands run without a shell.23use std::iter::Peekable;4use std::str::CharIndices;56/// Detects the variable assignment at the start of a command like7/// `OMP_NUM_THREADS=8 my_command`.8pub fn starts_with_assignment(command: &str) -> bool {9 let Some(token) = tokenize(command).next() else {10 return false;11 };12 let mut bytes = token.bytes();13 if !bytes14 .next()15 .is_some_and(|byte| byte.is_ascii_alphabetic() || byte == b'_')16 {17 return false;18 }19 for byte in bytes {20 if byte == b'=' {21 return true;22 }23 if !byte.is_ascii_alphanumeric() && byte != b'_' {24 return false;25 }26 }27 false28}2930/// Find the first standalone operator that is neither quoted nor escaped.31///32/// Operators attached to another word (such as `hello>out`), expansions, and33/// other shell syntax are deliberately outside the scope of this check.
79 unmodified lines
113}114115#[cfg(test)]116mod tests {93 use super::{first_unquoted_operator, tokenize};117 use super::{first_unquoted_operator, starts_with_assignment, tokenize};118119 #[test]120 fn detects_leading_assignments() {121 assert!(starts_with_assignment("A=1 command"));122 assert!(starts_with_assignment("A=$HOME command"));123 assert!(starts_with_assignment("A= command"));124 assert!(starts_with_assignment("_A2='hello world' B=2 command"));125 assert!(starts_with_assignment("A=1"));126 assert!(starts_with_assignment(" # comment\n A=1 command"));127128 assert!(!starts_with_assignment(""));129 assert!(!starts_with_assignment("# A=1 command"));130 assert!(!starts_with_assignment("command A=1"));131 assert!(!starts_with_assignment("env A=1 command"));132 assert!(!starts_with_assignment("'A=1' command"));133 assert!(!starts_with_assignment("\"A\"=1 command"));134 assert!(!starts_with_assignment(r"A\=1 command"));135 assert!(!starts_with_assignment("./A=1 command"));136 assert!(!starts_with_assignment("1A=1 command"));137 assert!(!starts_with_assignment("A-B=1 command"));138 assert!(!starts_with_assignment("=1 command"));139 assert!(!starts_with_assignment("A"));140 }141142 #[test]143 fn tokenizer_preserves_words_quotes_and_escapes() {144 for (command, expected) in [145 ("", vec![]),146 (" \t\n", vec![]),
119 unmodified lines
modified:tests/integration_tests.rs+60 added
51 unmodified lines
52 .assert()53 .success();54}5556#[test]57fn environment_basic_usage() {58 let command = if cfg!(windows) {59 "echo %HYPERFINE_TEST%"60 } else {61 "echo \"$HYPERFINE_TEST\""62 };63 hyperfine()64 .args(["--shell=default", "--runs=1", "--show-output"])65 .arg("--command-name=env-test")66 .args(["--env", r#"HYPERFINE_TEST="hello, world""#])67 .arg(command)68 .assert()69 .success()70 .stdout(predicate::str::contains("hello, world"));71}7273#[test]74fn environment_parameter_expansion() {75 let command = if cfg!(windows) {76 "echo %HYPERFINE_TEST%"77 } else {78 "echo \"$HYPERFINE_TEST\""79 };80 hyperfine()81 .args(["--shell=default", "--runs=1", "--show-output"])82 .arg("--command-name=env-test")83 .args(["-P", "value", "1", "2"])84 .args(["--env", "HYPERFINE_TEST=hello-{value}"])85 .arg(command)86 .assert()87 .success()88 .stdout(predicate::str::contains("hello-1"))89 .stdout(predicate::str::contains("hello-2"));90}9192#[test]93fn rejects_invalid_environment() {94 hyperfine()95 .args(["--env", "OMP_NUM_THREADS"])96 .arg("my_command")97 .assert()98 .failure()99 .stderr(predicate::str::contains(100 "Invalid value 'OMP_NUM_THREADS' for '--env': expected an assignment like NAME=value or NAME=\"quoted value\".",101 ));102}103104#[test]105fn requires_explicit_shell_for_environment_assignments() {106 // Without an explicit shell choice, report the leading variable assignment.107 hyperfine()108 .args(["--runs=1", "SOME_ENV_VAR=$HOME my_command"])109 .assert()110 .failure()111 .stderr(predicate::str::contains(112 "starts with a variable assignment",113 ));114}115116/// Regression test: hyperfine must not panic when writing to a closed117/// stdout pipe (e.g. `hyperfine ... | head -n 1` or a downstream process118/// that terminates early). A `BrokenPipe` error should result in a quiet119/// exit with code 0 instead of a `println!` panic.
1251 unmodified lines
modified:README.md+25 added
153 unmodified lines
154```sh155hyperfine -S 'my_function() { sleep 1; }; my_function'156```157158### Environment variables159160Use `--env` to set environment variables for benchmark commands and their respective setup, prepare, conclude,161and cleanup commands. Assignments are space-separated and support shell-style quoting,162but no shell expansion:163164```sh165hyperfine --env 'OMP_NUM_THREADS=8 CFLAGS="-O3 -march=native"' 'my_command'166```167168Specify once for all commands or once per benchmark command:169170```sh171hyperfine \172 --env 'OMP_NUM_THREADS=8' './benchmark-cpp' \173 --env 'RAYON_NUM_THREADS=8' './benchmark-rust'174```175176Use an empty `--env=''` for no overrides. Values can contain parameter placeholders.177For example, the following benchmarks `my_command` with `OMP_NUM_THREADS` ranging from 1 to 8:178179```sh180hyperfine -P threads 1 8 --env 'OMP_NUM_THREADS={threads}' 'my_command'181```182183### Choosing metrics and units184185By default, hyperfine displays wall-clock time and memory usage186(`time_wall_clock,memory_peak_resident`). Use `--metrics` with a
311 unmodified lines