cli.rs
This file
Path
src/cli.rs
422 lines · 19.3 KiB · Rust
Last changed by
Alternative performance metrics in the terminal (#986)David Peterbefore adoptionbdbfae9
History of this fileTake it
1use std::ffi::OsString;23use clap::{4 builder::styling::{AnsiColor, Effects},5 builder::NonEmptyStringValueParser,6 builder::Styles,7 crate_version, Arg, ArgAction, ArgMatches, Command, ValueHint,8};910pub const DEFAULT_METRICS: &str = if cfg!(windows) {11 "time_wall_clock"12} else {13 "time_wall_clock,memory_peak_resident"14};1516pub fn get_cli_arguments<'a, I, T>(args: I) -> ArgMatches17where18 I: IntoIterator<Item = T>,19 T: Into<OsString> + Clone + 'a,20{21 let command = build_command();22 command.get_matches_from(args)23}2425const STYLES: Styles = Styles::styled()26 .header(AnsiColor::Green.on_default().effects(Effects::BOLD))27 .usage(AnsiColor::Green.on_default().effects(Effects::BOLD))28 .literal(AnsiColor::Cyan.on_default().effects(Effects::BOLD))29 .placeholder(AnsiColor::Cyan.on_default());3031/// Build the clap command for parsing command line arguments32fn build_command() -> Command {33 Command::new("hyperfine")34 .version(crate_version!())35 .styles(STYLES)36 .next_line_help(true)37 .hide_possible_values(true)38 .about("A command-line benchmarking tool.")39 .help_expected(true)40 .max_term_width(80)41 .arg(42 Arg::new("command")43 .help("The command to benchmark. This can be the name of an executable, a command \44 line like \"grep -i todo\" or a shell command like \"sleep 0.5 && echo test\". \45 The latter requires a shell, which can be enabled via '-S' or '--shell=...'. \46 If multiple commands are given, hyperfine will show a \47 comparison with the first command as the reference.")48 .required(true)49 .action(ArgAction::Append)50 .value_hint(ValueHint::CommandString)51 .value_parser(NonEmptyStringValueParser::new()),52 )53 .arg(54 Arg::new("metrics")55 .long("metrics")56 .value_name("PRESET|METRIC[:UNIT],…")57 .default_value("default")58 .hide_default_value(true)59 .help("Performance metrics to measure, in order.\n\n\60 This is either a preset name, or a comma-separated list of metrics with optional units. \61 The first metric is used for non-JSON exports, \62 JSON always includes all collected metrics.\n\n\63 Presets (use one on its own):\n \64 default Wall-clock time and peak RSS\n \65 time Wall-clock, CPU, user, and system time\n \66 all All available metrics\n\n\67 Presets use automatic units.\n\n\68 Metrics and optional units:\n \69 Time: time_wall_clock, time_cpu, time_user, time_system\n \70 Units: ns, us, ms, s, min, h\n \71 Memory: memory_peak_resident\n \72 Units: B, kB, MB, GB, TB, KiB, MiB, GiB, TiB\n \73 Counters: cpu_cycles, instructions, cache_references,\n \74 cache_misses, branch_misses\n \75 Units: count, k (thousand), M (million), B (billion)\n\n\76 Examples:\n \77 --metrics time_cpu,instructions\n \78 --metrics memory_peak_resident:MiB,time_wall_clock:ms\n \79 --metrics time"),80 )81 .arg(82 Arg::new("warmup")83 .long("warmup")84 .short('w')85 .value_name("NUM")86 .action(ArgAction::Set)87 .value_parser(clap::value_parser!(u64))88 .help(89 "Perform NUM warmup runs before the actual benchmark. This can be used \90 to fill (disk) caches for I/O-heavy programs.",91 ),92 )93 .arg(94 Arg::new("min-runs")95 .long("min-runs")96 .short('m')97 .action(ArgAction::Set)98 .value_name("NUM")99 .value_parser(clap::value_parser!(u64).range(1..))100 .help("Perform at least NUM runs for each command (default: 10)."),101 )102 .arg(103 Arg::new("max-runs")104 .long("max-runs")105 .short('M')106 .action(ArgAction::Set)107 .value_name("NUM")108 .value_parser(clap::value_parser!(u64).range(1..))109 .help("Perform at most NUM runs for each command. By default, there is no limit."),110 )111 .arg(112 Arg::new("runs")113 .long("runs")114 .conflicts_with_all(["max-runs", "min-runs"])115 .short('r')116 .action(ArgAction::Set)117 .value_name("NUM")118 .value_parser(clap::value_parser!(u64).range(1..))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("setup")124 .long("setup")125 .short('s')126 .action(ArgAction::Set)127 .value_name("CMD")128 .value_hint(ValueHint::CommandString)129 .help(130 "Execute CMD before each set of benchmark runs. This is useful for \131 compiling your software with the provided parameters, or to do any \132 other work that should happen once before a series of benchmark runs, \133 not every time as would happen with the --prepare option."134 ),135 )136 .arg(137 Arg::new("prepare")138 .long("prepare")139 .short('p')140 .action(ArgAction::Append)141 .num_args(1)142 .value_name("CMD")143 .value_hint(ValueHint::CommandString)144 .help(145 "Execute CMD before each benchmark run. This is useful for \146 clearing disk caches, for example.\nThe --prepare option can \147 be specified once for all commands or multiple times, once for \148 each command. In the latter case, each preparation command will \149 be run prior to the corresponding benchmark command.",150 ),151 )152 .arg(153 Arg::new("conclude")154 .long("conclude")155 .short('C')156 .action(ArgAction::Append)157 .num_args(1)158 .value_name("CMD")159 .value_hint(ValueHint::CommandString)160 .help(161 "Execute CMD after each benchmark run. This is useful for killing \162 long-running processes started (e.g. a web server started in --prepare), \163 for example.\nThe --conclude option can be specified once for all \164 commands or multiple times, once for each command. In the latter case, \165 each conclude command will be run after the corresponding benchmark \166 command.",167 ),168 )169 .arg(170 Arg::new("cleanup")171 .long("cleanup")172 .short('c')173 .action(ArgAction::Set)174 .value_name("CMD")175 .value_hint(ValueHint::CommandString)176 .help(177 "Execute CMD after the completion of all benchmarking \178 runs for each individual command to be benchmarked. \179 This is useful if the commands to be benchmarked produce \180 artifacts that need to be cleaned up."181 ),182 )183 .arg(184 Arg::new("parameter-scan")185 .long("parameter-scan")186 .short('P')187 .action(ArgAction::Set)188 .allow_hyphen_values(true)189 .value_names(["VAR", "MIN", "MAX"])190 .help(191 "Perform benchmark runs for each value in the range MIN..MAX. Replaces the \192 string '{VAR}' in each command by the current parameter value.\n\n \193 Example: hyperfine --prepare 'make clean' -P threads 1 8 'make -j {threads}'\n\n\194 This performs benchmarks for 'make -j 1', 'make -j 2', …, 'make -j 8'.\n\n\195 To have the value increase following different patterns, use shell arithmetic.\n\n \196 Example: hyperfine --shell=bash -P size 0 3 'sleep $((2**{size}))'\n\n\197 This performs benchmarks with power of 2 increases: 'sleep 1', 'sleep 2', 'sleep 4', …\n\198 The exact syntax may vary depending on your shell and OS."199 ),200 )201 .arg(202 Arg::new("parameter-step-size")203 .long("parameter-step-size")204 .short('D')205 .action(ArgAction::Set)206 .value_names(["DELTA"])207 .requires("parameter-scan")208 .help(209 "This argument requires --parameter-scan to be specified as well. \210 Traverse the range MIN..MAX in steps of DELTA, which must be positive.\n\n \211 Example: hyperfine -P delay 0.3 0.7 -D 0.2 'sleep {delay}'\n\n\212 This performs benchmarks for 'sleep 0.3', 'sleep 0.5' and 'sleep 0.7'.",213 ),214 )215 .arg(216 Arg::new("parameter-list")217 .long("parameter-list")218 .short('L')219 .action(ArgAction::Append)220 .allow_hyphen_values(true)221 .value_names(["VAR", "VALUES"])222 .conflicts_with_all(["parameter-scan", "parameter-step-size"])223 .help(224 "Perform benchmark runs for each value in the comma-separated list VALUES. \225 Replaces the string '{VAR}' in each command by the current parameter value\226 .\n\nExample: hyperfine -L compiler g++,clang++ '{compiler} -O2 main.cpp'\n\n\227 This performs benchmarks for 'g++ -O2 main.cpp' and 'clang++ -O2 main.cpp'.\n\n\228 The option can be specified multiple times to run benchmarks for all \229 possible parameter combinations.\n"230 ),231 )232 .arg(233 Arg::new("shell")234 .long("shell")235 .action(ArgAction::Set)236 .value_name("SHELL")237 .overrides_with("shell")238 .value_hint(ValueHint::CommandString)239 .help("Set the shell to use for executing commands (default: none). This can be the \240 name or the path to the shell executable, or a full command line \241 like \"bash --norc\". It can also be set to \"default\" to explicitly select \242 the platform shell (sh on Unix, cmd.exe on Windows). It can also be set to \243 \"none\" to disable the shell. In this case, commands will be executed \244 directly. They can still have arguments, but more complex things like \245 \"sleep 0.1; sleep 0.2\" are not possible without a shell. This option also \246 applies to setup, prepare, conclude, and cleanup commands.")247 )248 .arg(249 Arg::new("default-shell")250 .short('S')251 .action(ArgAction::SetTrue)252 .conflicts_with_all(["shell", "no-shell", "debug-mode"])253 .help("An alias for '--shell=default' (sh on Unix, cmd.exe on Windows).")254 )255 .arg(256 Arg::new("no-shell")257 .short('N')258 .action(ArgAction::SetTrue)259 .conflicts_with_all(["shell", "debug-mode"])260 .help("An alias for '--shell=none'.")261 )262 .arg(263 Arg::new("ignore-failure")264 .long("ignore-failure")265 .action(ArgAction::Set)266 .value_name("MODE")267 .num_args(0..=1)268 .default_missing_value("all-non-zero")269 .require_equals(true)270 .short('i')271 .help("Ignore failures of the benchmarked programs. Without a value or with \272 'all-non-zero', all non-zero exit codes are ignored. You can also provide \273 a comma-separated list of exit codes to ignore (e.g., --ignore-failure=1,2)."),274 )275 .arg(276 Arg::new("style")277 .long("style")278 .action(ArgAction::Set)279 .value_name("TYPE")280 .value_parser(["auto", "basic", "full", "nocolor", "color", "none"])281 .help(282 "Set output style type (default: auto). Set this to 'basic' to disable output \283 coloring and interactive elements. Set it to 'full' to enable all effects \284 even if no interactive terminal was detected. Set this to 'nocolor' to \285 keep the interactive output without any colors. Set this to 'color' to keep \286 the colors without any interactive output. Set this to 'none' to disable all \287 the output of the tool.",288 ),289 )290 .arg(291 Arg::new("export-asciidoc")292 .long("export-asciidoc")293 .action(ArgAction::Set)294 .value_name("FILE")295 .value_hint(ValueHint::FilePath)296 .help("Export the primary metric summary statistics as an AsciiDoc table to the given FILE. \297 The unit can be set with --metrics METRIC:UNIT."),298 )299 .arg(300 Arg::new("export-csv")301 .long("export-csv")302 .action(ArgAction::Set)303 .value_name("FILE")304 .value_hint(ValueHint::FilePath)305 .help("Export the primary metric summary statistics as CSV to the given FILE. If you need \306 all metrics for each individual run, use the JSON export format. \307 Use the explicitly selected unit, or the base unit when unspecified."),308 )309 .arg(310 Arg::new("export-json")311 .long("export-json")312 .action(ArgAction::Set)313 .value_name("FILE")314 .value_hint(ValueHint::FilePath)315 .help("Export all collected metrics and individual runs as JSON to the given FILE. \316 Values always use base units (seconds, bytes, counts)."),317 )318 .arg(319 Arg::new("export-markdown")320 .long("export-markdown")321 .action(ArgAction::Set)322 .value_name("FILE")323 .value_hint(ValueHint::FilePath)324 .help("Export the primary metric summary statistics as a Markdown table to the given FILE. \325 The unit can be set with --metrics METRIC:UNIT."),326 )327 .arg(328 Arg::new("export-orgmode")329 .long("export-orgmode")330 .action(ArgAction::Set)331 .value_name("FILE")332 .value_hint(ValueHint::FilePath)333 .help("Export the primary metric summary statistics as an Emacs org-mode table to the given FILE. \334 The unit can be set with --metrics METRIC:UNIT."),335 )336 .arg(337 Arg::new("show-output")338 .long("show-output")339 .action(ArgAction::SetTrue)340 .conflicts_with("style")341 .help(342 "Print the stdout and stderr of the benchmark instead of suppressing it. \343 This will increase the time it takes for benchmarks to run, \344 so it should only be used for debugging purposes or \345 when trying to benchmark output speed.",346 ),347 )348 .arg(349 Arg::new("output")350 .long("output")351 .conflicts_with("show-output")352 .action(ArgAction::Append)353 .value_name("WHERE")354 .help(355 "Control where the output of the benchmark is redirected. Note \356 that some programs like 'grep' detect when standard output is \357 /dev/null and apply certain optimizations. To avoid that, consider \358 using '--output=pipe'.\n\359 \n\360 <WHERE> can be:\n\361 \n \362 null: Redirect output to /dev/null (the default).\n\363 \n \364 pipe: Feed the output through a pipe before discarding it.\n\365 \n \366 inherit: Don't redirect the output at all (same as '--show-output').\n\367 \n \368 <FILE>: Write the output to the given file.\n\n\369 This option can be specified once for all commands or multiple times, once for \370 each command. Note: If you want to log the output of each and every iteration, \371 you can use a shell redirection and the '$HYPERFINE_ITERATION' environment variable:\n \372 hyperfine -S 'my-command > output-${HYPERFINE_ITERATION}.log'\n\n",373 ),374 )375 .arg(376 Arg::new("input")377 .long("input")378 .action(ArgAction::Set)379 .num_args(1)380 .value_name("WHERE")381 .help("Control where the input of the benchmark comes from.\n\382 \n\383 <WHERE> can be:\n\384 \n \385 null: Read from /dev/null (the default).\n\386 \n \387 <FILE>: Read the input from the given file."),388 )389 .arg(390 Arg::new("command-name")391 .long("command-name")392 .short('n')393 .action(ArgAction::Append)394 .num_args(1)395 .value_name("NAME")396 .help("Give a meaningful name to a command. This can be specified multiple times \397 if several commands are benchmarked."),398 )399 // This option is hidden for now, as it is not yet clear yet if we want to 'stabilize' this,400 // see discussion in https://github.com/sharkdp/hyperfine/issues/527401 .arg(402 Arg::new("min-benchmarking-time")403 .long("min-benchmarking-time")404 .action(ArgAction::Set)405 .hide(true)406 .help("Set the minimum time (in seconds) to run benchmarks. Note that the number of \407 benchmark runs is additionally influenced by the `--min-runs`, `--max-runs`, and \408 `--runs` option.")409 )410 .arg(411 Arg::new("debug-mode")412 .long("debug-mode")413 .action(ArgAction::SetTrue)414 .hide(true)415 .help("Enable debug mode which does not actually run commands, but returns fake times when the command is 'sleep <time>'.")416 )417}418419#[test]420fn verify_app() {421 build_command().debug_assert();422}