This is a library for human readable elapsed time string
Rust 1.58 or newer
Put this in your Cargo.toml
:
toml
[dependencies]
human-time="0"
Convert a duration to a human readable string
```rust use std::{ thread, time::{Duration, Instant}, };
use human_time::ToHumanTimeString;
fn main() { let start = Instant::now(); thread::sleep(Duration::fromsecs(1)); let costs: Duration = start.elapsed(); println!("costs {}", costs.tohumantimestring());
println!(
"costs {}",
Duration::from_secs(88401 * 2 * 8).to_human_time_string()
);
println!(
"costs {}",
Duration::from_millis(8840003).to_human_time_string()
);
} ```
Output
```text
costs 1s,202μs costs 16d,8h,53m,36s costs 2h,27m,20s,3ms ```
Convert a duration to a human readable string with format.
```rust use std::time::Duration;
use human_time::ToHumanTimeString;
fn main() { println!( "costs {}", Duration::frommillis(8840003).tohumantimestringwithformat( |n, unit| { format!( "{n}{}", match unit { "d" => "days".toowned(), "h" => "hours".toowned(), "m" => "minutes".toowned(), "s" => "seconds".toowned(), "ms" => "ms".toowned(), other => other.tostring(), } ) }, |acc, item| format!("{} {}", acc, item) ) ); } ```
Output
text
costs 2hours 27minutes 20seconds 3ms
Print function time-consuming with elapsed macro
```rust use std::{fmt::Display, thread, time::Duration};
fn main() { foo(1); }
//use log::debug; //#[humantime::elapsed(output = "debug")] //#[humantime::elapsed(output = "eprintln")] // #[human_time::elapsed(output = "println")] //default
fn foo
async fn bar() { thread::sleep(Duration::from_millis(1000)); } ```
Output
text
fn foo costs 1s,2ms,837μs