Skip to content
Myr

cli.rs

This file

Path

src/cli.rs

400 lines · 17.9 KiB · Rust

Last changed by

Multiple output policiesDavid Peterbefore adoption99d24b7

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