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

human-time

这是一个人类可读的已过时间字符串库。

7 个版本

0.1.6 2023 年 1 月 3 日
0.1.5 2022 年 12 月 26 日

#89值格式化

Download history 799/week @ 2024-03-13 1015/week @ 2024-03-20 448/week @ 2024-03-27 877/week @ 2024-04-03 1049/week @ 2024-04-10 975/week @ 2024-04-17 965/week @ 2024-04-24 828/week @ 2024-05-01 787/week @ 2024-05-08 933/week @ 2024-05-15 707/week @ 2024-05-22 559/week @ 2024-05-29 801/week @ 2024-06-05 685/week @ 2024-06-12 831/week @ 2024-06-19 944/week @ 2024-06-26

3,462 每月下载
用于 2 crates

Apache-2.0

7KB
57

人类可读的已过时间字符串

概览

这是一个人类可读的已过时间字符串库。

先决条件

Rust 1.58 或更高版本

使用方法

将以下内容放入您的 Cargo.toml

[dependencies]
human-time="0"

示例

将持续时间转换为人类可读的字符串

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()
    );
}

输出


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

使用格式将持续时间转换为人类可读的字符串。

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)
        )
    );
}

输出

costs 2hours 27minutes 20seconds 3ms

使用 elapsed 宏打印耗时函数

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));
}

输出

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

依赖项

~1.5MB
~36K SLoC