Skip to content
Myr

cli.rs

This file

Path

src/cli.rs

459 lines · 21.5 KiB · Rust

Last changed by

Add migration guidance for removed --reference optionDavid Peterbefore adoption26760e8

History of this file

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