Skip to content

Commit

Permalink
Add style key for speed in steps/bytes per second (#108)
Browse files Browse the repository at this point in the history
  • Loading branch information
kpcyrd authored and mitsuhiko committed Sep 7, 2019
1 parent 958dc9b commit 9729504
Show file tree
Hide file tree
Showing 4 changed files with 38 additions and 0 deletions.
24 changes: 24 additions & 0 deletions examples/download-speed.rs
@@ -0,0 +1,24 @@
use std::cmp::min;
use std::thread;
use std::time::Duration;

use indicatif::{ProgressBar, ProgressStyle};

fn main() {
let mut downloaded = 0;
let total_size = 231231231;

let pb = ProgressBar::new(total_size);
pb.set_style(ProgressStyle::default_bar()
.template("{spinner:.green} [{elapsed_precise}] [{bar:40.cyan/blue}] {bytes}/{total_bytes} ({bytes_per_sec}, {eta})")
.progress_chars("#>-"));

while downloaded < total_size {
let new = min(downloaded + 223211, total_size);
downloaded = new;
pb.set_position(new);
thread::sleep(Duration::from_millis(12));
}

pb.finish_with_message("downloaded");
}
2 changes: 2 additions & 0 deletions src/lib.rs
Expand Up @@ -156,6 +156,8 @@
//! * `total_bytes`: renders the total length of the bar as bytes.
//! * `elapsed_precise`: renders the elapsed time as `HH:MM:SS`.
//! * `elapsed`: renders the elapsed time as `42s`, `1m` etc.
//! * `per_sec`: renders the speed in steps per second.
//! * `bytes_per_sec`: renders the speed in bytes per second.
//! * `eta_precise`: the remaining time (like `elapsed_precise`).
//! * `eta`: the remaining time (like `elapsed`).
//!
Expand Down
10 changes: 10 additions & 0 deletions src/progress.rs
Expand Up @@ -302,6 +302,16 @@ impl ProgressState {
// add 0.75 to leave 0.25 sec of 0s for the user
secs_to_duration(t * self.len.saturating_sub(self.pos) as f64 + 0.75)
}

/// The number of steps per second
pub fn per_sec(&self) -> u64 {
let avg_time = self.avg_time_per_step().as_nanos();
if avg_time == 0 {
0
} else {
(1_000_000_000 / avg_time) as u64
}
}
}

/// A progress bar or spinner.
Expand Down
2 changes: 2 additions & 0 deletions src/style.rs
Expand Up @@ -142,6 +142,8 @@ impl ProgressStyle {
"binary_total_bytes" => format!("{}", BinaryBytes(state.len)),
"elapsed_precise" => format!("{}", FormattedDuration(state.started.elapsed())),
"elapsed" => format!("{:#}", HumanDuration(state.started.elapsed())),
"per_sec" => format!("{}/s", state.per_sec()),
"bytes_per_sec" => format!("{}/s", HumanBytes(state.per_sec())),
"eta_precise" => format!("{}", FormattedDuration(state.eta())),
"eta" => format!("{:#}", HumanDuration(state.eta())),
_ => "".into(),
Expand Down

0 comments on commit 9729504

Please sign in to comment.