Skip to content
Myr

cli.rs

This file

Path

src/cli.rs

418 lines · 18.8 KiB · Rust

Last changed by

Fix panic on --runs 0 (#923)Vincentbefore adoption907de26

History of this file

Take it

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