#elapsed-time #human-readable #duration-string #duration #human #elapsed #time

human-time

This is a library for human readable elapsed time string

7 releases

0.1.6 Jan 3, 2023
0.1.5 Dec 26, 2022

#134 in Value formatting

Download history 561/week @ 2024-06-11 896/week @ 2024-06-18 904/week @ 2024-06-25 1203/week @ 2024-07-02 756/week @ 2024-07-09 1387/week @ 2024-07-16 1235/week @ 2024-07-23 1235/week @ 2024-07-30 1155/week @ 2024-08-06 1712/week @ 2024-08-13 542/week @ 2024-08-20 773/week @ 2024-08-27 998/week @ 2024-09-03 1059/week @ 2024-09-10 1230/week @ 2024-09-17 1119/week @ 2024-09-24

4,529 downloads per month
Used in 2 crates

Apache-2.0

7KB
57 lines

Human readable elapsed time string

Overview

This is a library for human readable elapsed time string

Prerequisites

Rust 1.58 or newer

Usage

Put this in your Cargo.toml:

[dependencies]
human-time="0"

Examples

Convert a duration to a human readable string

use std::{
    thread,
    time::{Duration, Instant},
};

use human_time::ToHumanTimeString;

fn main() {
    let start = Instant::now();
    thread::sleep(Duration::from_secs(1));
    let costs: Duration = start.elapsed();
    println!("costs {}", costs.to_human_time_string());

    println!(
        "costs {}",
        Duration::from_secs(88401 * 2 * 8).to_human_time_string()
    );
    println!(
        "costs {}",
        Duration::from_millis(8840003).to_human_time_string()
    );
}

Output


costs 1s,202μs
costs 16d,8h,53m,36s
costs 2h,27m,20s,3ms

Convert a duration to a human readable string with format.

use std::time::Duration;

use human_time::ToHumanTimeString;

fn main() {
    println!(
        "costs {}",
        Duration::from_millis(8840003).to_human_time_string_with_format(
            |n, unit| {
                format!(
                    "{n}{}",
                    match unit {
                        "d" => "days".to_owned(),
                        "h" => "hours".to_owned(),
                        "m" => "minutes".to_owned(),
                        "s" => "seconds".to_owned(),
                        "ms" => "ms".to_owned(),
                        other => other.to_string(),
                    }
                )
            },
            |acc, item| format!("{} {}", acc, item)
        )
    );
}

Output

costs 2hours 27minutes 20seconds 3ms

Print function time-consuming with elapsed macro

use std::{fmt::Display, thread, time::Duration};

fn main() {
    foo(1);
}

//use log::debug;
//#[human_time::elapsed(output = "debug")]
//#[human_time::elapsed(output = "eprintln")]
// #[human_time::elapsed(output = "println")] //default
#[human_time::elapsed()]
fn foo<T>(_x: T)
where
    T: Display,
{
    thread::sleep(Duration::from_millis(1000));
}

#[human_time::elapsed(output = "eprintln")]
async fn bar() {
    thread::sleep(Duration::from_millis(1000));
}

Output

fn foo costs 1s,2ms,837μs

Dependencies

~1.5MB
~35K SLoC