Skip to content
Myr

progress_bar.rs

This file

Path

src/output/progress_bar.rs

70 lines · 2.6 KiB · Rust

Last changed by

Alternative performance metrics in the terminal (#986)David Peterbefore adoptionbdbfae9

History of this file

Take it

1use indicatif::{FormattedDuration, ProgressBar, ProgressState, ProgressStyle};2use std::fmt;3use std::time::{Duration, Instant};45use crate::options::OutputStyleOption;67#[cfg(not(windows))]8const TICK_SETTINGS: (&str, u64) = ("⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏ ", 80);910#[cfg(windows)]11const TICK_SETTINGS: (&str, u64) = (r"+-x| ", 200);1213// Keep the message area 30 columns wide across preparation, the initial run,14// and estimates so that switching between them does not move the bar.15const DEFAULT_TEMPLATE: &str = " {spinner} {msg:<30} {wide_bar} ETA {eta_precise} ";16const INITIAL_TEMPLATE: &str =17    " {spinner} Initial run: {initial_elapsed:<17} {wide_bar} ETA {eta_precise} ";1819fn style_with_template(bar: &ProgressBar, template: &str) -> ProgressStyle {20    let template = if bar.prefix().is_empty() {21        template.to_owned()22    } else {23        format!("{{prefix}}\n{template}")24    };25    bar.style().template(&template).expect("no template error")26}2728/// Show the benchmark heading above the progress bar, clearing both on completion.29pub fn set_benchmark_header(bar: &ProgressBar, header: String) {30    bar.set_prefix(header);31    bar.set_style(style_with_template(bar, DEFAULT_TEMPLATE));32}3334/// Show the time elapsed since the initial benchmark command started.35pub fn start_initial_measurement(bar: &ProgressBar, started: Instant) {36    let style = style_with_template(bar, INITIAL_TEMPLATE).with_key(37        "initial_elapsed",38        move |_: &ProgressState, w: &mut dyn fmt::Write| {39            write!(w, "{}", FormattedDuration(started.elapsed())).unwrap();40        },41    );42    bar.set_style(style);43}4445/// Stop showing the initial timer and display the next phase's message.46pub fn finish_initial_measurement(bar: &ProgressBar, message: String) {47    bar.set_message(message);48    bar.set_style(style_with_template(bar, DEFAULT_TEMPLATE));49}5051/// Return a pre-configured progress bar52pub fn get_progress_bar(length: u64, msg: &str, option: OutputStyleOption) -> ProgressBar {53    let progressbar_style = match option {54        OutputStyleOption::Basic | OutputStyleOption::Color => ProgressStyle::default_bar(),55        _ => ProgressStyle::default_spinner()56            .tick_chars(TICK_SETTINGS.0)57            .template(DEFAULT_TEMPLATE)58            .expect("no template error"),59    };6061    let progress_bar = match option {62        OutputStyleOption::Basic | OutputStyleOption::Color => ProgressBar::hidden(),63        _ => ProgressBar::new(length),64    };65    progress_bar.set_style(progressbar_style);66    progress_bar.enable_steady_tick(Duration::from_millis(TICK_SETTINGS.1));67    progress_bar.set_message(msg.to_owned());6869    progress_bar70}