Skip to content
Myr

main.rs

This file

Path

src/main.rs

167 lines · 4.9 KiB · Rust

Last changed by

Initial working version with child proc HANDLE.Steve Pentlandbefore adoption9753eed

History of this file

Take it

1extern crate atty;2#[macro_use]3extern crate clap;4extern crate colored;5extern crate indicatif;6extern crate statistical;78#[cfg(not(windows))]9extern crate libc;1011#[cfg(windows)]12extern crate winapi;1314#[cfg(test)]15#[macro_use]16extern crate approx;1718use std::cmp;19use std::error::Error;20use std::io;2122use atty::Stream;23use colored::*;24use clap::{App, AppSettings, Arg};2526mod hyperfine;2728use hyperfine::internal::{CmdFailureAction, HyperfineOptions, OutputStyleOption};29use hyperfine::benchmark::{mean_shell_spawning_time, run_benchmark};3031/// Print error message to stderr and terminate32pub fn error(message: &str) -> ! {33    eprintln!("{} {}", "Error:".red(), message);34    std::process::exit(1);35}3637/// Runs the benchmark for the given commands38fn run(commands: &Vec<&str>, options: &HyperfineOptions) -> io::Result<()> {39    let shell_spawning_time = mean_shell_spawning_time(&options.output_style)?;4041    // Run the benchmarks42    for (num, cmd) in commands.iter().enumerate() {43        run_benchmark(num, cmd, shell_spawning_time, options)?;44    }4546    Ok(())47}4849fn main() {50    // Process command line options51    let mut options = HyperfineOptions::default();5253    let clap_color_setting = if atty::is(Stream::Stdout) {54        AppSettings::ColoredHelp55    } else {56        AppSettings::ColorNever57    };5859    let matches = App::new("hyperfine")60        .version(crate_version!())61        .setting(clap_color_setting)62        .setting(AppSettings::DeriveDisplayOrder)63        .setting(AppSettings::UnifiedHelpMessage)64        .max_term_width(90)65        .about("A command-line benchmarking tool.")66        .arg(67            Arg::with_name("command")68                .help("Command to benchmark")69                .required(true)70                .multiple(true)71                .empty_values(false),72        )73        .arg(74            Arg::with_name("warmup")75                .long("warmup")76                .short("w")77                .takes_value(true)78                .value_name("NUM")79                .help(80                    "Perform NUM warmup runs before the actual benchmark. This can be used \81                     to fill (disk) caches for I/O-heavy programs.",82                ),83        )84        .arg(85            Arg::with_name("min-runs")86                .long("min-runs")87                .short("m")88                .takes_value(true)89                .value_name("NUM")90                .help(&format!(91                    "Perform at least NUM runs for each command (default: {}).",92                    options.min_runs93                )),94        )95        .arg(96            Arg::with_name("prepare")97                .long("prepare")98                .short("p")99                .takes_value(true)100                .value_name("CMD")101                .help(102                    "Execute CMD before each timing run. This is useful for \103                     clearing disk caches, for example.",104                ),105        )106        .arg(107            Arg::with_name("style")108                .long("style")109                .short("s")110                .takes_value(true)111                .value_name("TYPE")112                .possible_values(&["auto", "basic", "full"])113                .help(114                    "Set output style type (default: auto). Set this to 'basic' to disable output \115                     coloring and interactive elements. Set it to 'full' to enable all effects \116                     even if no interactive terminal was detected.",117                ),118        )119        .arg(120            Arg::with_name("ignore-failure")121                .long("ignore-failure")122                .short("i")123                .help("Ignore non-zero exit codes."),124        )125        .help_message("Print this help message.")126        .version_message("Show version information.")127        .get_matches();128129    let str_to_u64 = |n| u64::from_str_radix(n, 10).ok();130131    options.warmup_count = matches132        .value_of("warmup")133        .and_then(&str_to_u64)134        .unwrap_or(0);135136    if let Some(min_runs) = matches.value_of("min-runs").and_then(&str_to_u64) {137        // we need at least two runs to compute a variance138        options.min_runs = cmp::max(2, min_runs);139    }140141    options.preparation_command = matches.value_of("prepare").map(String::from);142143    options.output_style = match matches.value_of("style") {144        Some("full") => OutputStyleOption::Full,145        Some("basic") => OutputStyleOption::Basic,146        _ => if atty::is(Stream::Stdout) {147            OutputStyleOption::Full148        } else {149            OutputStyleOption::Basic150        },151    };152153    if options.output_style == OutputStyleOption::Basic {154        colored::control::set_override(false);155    }156157    if matches.is_present("ignore-failure") {158        options.failure_action = CmdFailureAction::Ignore;159    }160161    let commands = matches.values_of("command").unwrap().collect();162    let res = run(&commands, &options);163164    if let Err(e) = res {165        error(e.description());166    }167}