Skip to content

Commit

Permalink
fix time formatting
Browse files Browse the repository at this point in the history
closes #2
Uses time formatting approach based on humantime, but skips some time details after some thresholds.

skip seconds after one hour
skip minutes after one day
skip hours after 30 days

For millisecond:
1. Skipp above 30seconds
2. Between 30sec and 1 sec show rounded ms
3. Below 1 sec round to two digits
  • Loading branch information
PSeitz committed Nov 4, 2021
1 parent 9fc46c4 commit bd82934
Show file tree
Hide file tree
Showing 3 changed files with 224 additions and 54 deletions.
26 changes: 6 additions & 20 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -1,24 +1,10 @@
This is free and unencumbered software released into the public domain.
Includes portions of humantime
Copyright (c) 2016 The humantime Developers

Anyone is free to copy, modify, publish, use, compile, sell, or
distribute this software, either in source code form or as a compiled
binary, for any purpose, commercial or non-commercial, and by any
means.
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

In jurisdictions that recognize copyright laws, the author or authors
of this software dedicate any and all copyright interest in the
software to the public domain. We make this dedication for the benefit
of the public at large and to the detriment of our heirs and
successors. We intend this dedication to be an overt act of
relinquishment in perpetuity of all present and future rights to this
software under copyright law.
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.

For more information, please refer to <http://unlicense.org>
182 changes: 182 additions & 0 deletions src/formatted_duration.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,182 @@
use std::{fmt, time::Duration};

/// A wrapper type that allows you to Display a Duration
#[derive(Debug, Clone)]
pub struct FormattedDuration(Duration);

pub fn format_duration(val: Duration) -> FormattedDuration {
FormattedDuration(val)
}

fn item_plural(f: &mut fmt::Formatter, started: &mut bool, name: &str, value: u64) -> fmt::Result {
if value > 0 {
if *started {
f.write_str(" ")?;
}
write!(f, "{}{}", value, name)?;
if value > 1 {
f.write_str("s")?;
}
*started = true;
}
Ok(())
}
fn item_ms(
f: &mut fmt::Formatter,
started: &mut bool,
name: &str,
duration: Duration,
) -> fmt::Result {
// Three cases
// 1. Above 30seconds, we dont' show ms anymore
// 2. Between 30sec and 1 sec we don't show rounded ms
// 3. Below we round to two digits
if Duration::new(30, 0) < duration {
return Ok(());
}
if Duration::new(1, 0) < duration {
if *started {
f.write_str(" ")?;
}
write!(f, "{}{}", (duration.subsec_nanos() / 1_000_000), name)?;
*started = true;
return Ok(());
}
//show rounded
if *started {
f.write_str(" ")?;
}
write!(
f,
"{}{}",
(duration.subsec_nanos() / 1_000_0) as f32 / 100.,
name
)?;
*started = true;
Ok(())
}
fn item(
f: &mut fmt::Formatter,
started: &mut bool,
name: &str,
value: u32,
skip: bool,
) -> fmt::Result {
if skip {
return Ok(());
}
if value > 0 {
if *started {
f.write_str(" ")?;
}
write!(f, "{}{}", value, name)?;
*started = true;
}
Ok(())
}

const ONE_MINUTE_IN_SECONDS: u64 = 60;
const ONE_HOURS_IN_SECONDS: u64 = ONE_MINUTE_IN_SECONDS * 60;
const ONE_DAY_IN_SECONDS: u64 = ONE_HOURS_IN_SECONDS * 24;

impl fmt::Display for FormattedDuration {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let secs = self.0.as_secs();
let nanos = self.0.subsec_nanos();

if secs == 0 && nanos == 0 {
f.write_str("0s")?;
return Ok(());
}

let years = secs / 31_557_600; // 365.25d
let ydays = secs % 31_557_600;
let months = ydays / 2_630_016; // 30.44d
let mdays = ydays % 2_630_016;
let days = mdays / 86400;
let day_secs = mdays % 86400;
let hours = day_secs / 3600;
let minutes = day_secs % 3600 / 60;
let seconds = day_secs % 60;

let ref mut started = false;
item_plural(f, started, "year", years)?;
item_plural(f, started, "month", months)?;
item_plural(f, started, "day", days)?;

item(
f,
started,
"h",
hours as u32,
self.0 > Duration::from_secs(ONE_DAY_IN_SECONDS * 30), // skip hours after 30 days
)?;
item(
f,
started,
"m",
minutes as u32,
self.0 > Duration::from_secs(ONE_DAY_IN_SECONDS), // skip minutes after one day
)?;
item(
f,
started,
"s",
seconds as u32,
self.0 > Duration::from_secs(ONE_HOURS_IN_SECONDS * 3), // skip seconds after one hour
)?;
item_ms(f, started, "ms", self.0)?;
Ok(())
}
}

pub fn human_readable_time(duration: Duration) -> String {
format_duration(duration).to_string()
}

#[test]
fn human_readable_time_test() {
assert_eq!(
human_readable_time(Duration::new(5, 900_000_000)),
"5s 900ms"
);
assert_eq!(
human_readable_time(Duration::new(ONE_HOURS_IN_SECONDS + 1, 900_123_000)),
"1h 1s"
);
assert_eq!(
human_readable_time(Duration::new(ONE_HOURS_IN_SECONDS - 1, 900_123_000)),
"59m 59s"
);
assert_eq!(
human_readable_time(Duration::new(3 * ONE_HOURS_IN_SECONDS + 1, 900_123_000)),
"3h"
);
assert_eq!(
human_readable_time(Duration::new(5, 900_123_000)),
"5s 900ms"
);
assert_eq!(
human_readable_time(Duration::new(
ONE_HOURS_IN_SECONDS * 10 + ONE_MINUTE_IN_SECONDS * 10 + 10, // don't print seconds
123
)),
"10h 10m"
);
assert_eq!(
human_readable_time(Duration::new(
ONE_HOURS_IN_SECONDS * 10 + ONE_MINUTE_IN_SECONDS,
123
)),
"10h 1m"
);
assert_eq!(
human_readable_time(Duration::new(ONE_HOURS_IN_SECONDS * 3 + 10, 123)),
"3h"
);
assert_eq!(human_readable_time(Duration::new(0, 900_000)), "0.9ms");
assert_eq!(human_readable_time(Duration::new(0, 950_000)), "0.95ms");
assert_eq!(human_readable_time(Duration::new(0, 1950_000)), "1.95ms");
assert_eq!(human_readable_time(Duration::new(0, 1950_000)), "1.95ms");
assert_eq!(human_readable_time(Duration::new(0, 1957_123)), "1.95ms");
}
70 changes: 36 additions & 34 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,13 @@
//! ```
//!
extern crate log;
use std::time::Duration;

use formatted_duration::human_readable_time;
pub use log::*;

mod formatted_duration;

#[macro_export]
macro_rules! log_time {
(target: $target:expr, $lvl:expr, $lvl2:expr, $($arg:tt)+) => (
Expand Down Expand Up @@ -84,32 +89,6 @@ macro_rules! trace_time {
#[macro_export]
macro_rules! print_time {($($arg:tt)+) => {#[allow(unused_variables)] let time = $crate::MeasureTime::new(module_path!(), module_path!(), file!(), line!(), format!($($arg)+), $crate::LevelFilter::Off); } }

#[cfg(test)]
mod tests {
#[test]
fn funcy_func() {
trace_time!("{:?}", "trace");
debug_time!("{:?}", "debug");
info_time!("measure function");
{
debug_time!("{:?}", "measuring block");
let mut sum = 0;
for el in 0..50000 {
sum += el;
}
println!("{:?}", sum);
}

print_time!("print");
error_time!("error_time");

trace_time!(target: "trace_time", "custom target");
debug_time!(target: "debug_time", "custom target");
info_time!(target: "info_time", "custom target");
error_time!(target: "measure_time", "custom target");
}
}

#[derive(Debug)]
pub struct MeasureTime {
name: String,
Expand Down Expand Up @@ -143,14 +122,8 @@ impl MeasureTime {

impl Drop for MeasureTime {
fn drop(&mut self) {
let time_in_ms = (self.start.elapsed().as_secs() as f64 * 1_000.0)
+ (self.start.elapsed().subsec_nanos() as f64 / 1000_000.0);

let time = match time_in_ms as u64 {
0..=3000 => format!("{}ms", time_in_ms),
3001..=60000 => format!("{:.2}s", time_in_ms / 1000.0),
_ => format!("{:.2}m", time_in_ms / 1000.0 / 60.0),
};
let time = human_readable_time(self.start.elapsed());
//let time = human_readable_time(time_in_ms);

if let Some(level) = self.level.to_level() {
log::logger().log(
Expand All @@ -168,3 +141,32 @@ impl Drop for MeasureTime {
}
}
}

#[cfg(test)]
mod tests {

use super::*;

#[test]
fn funcy_func() {
trace_time!("{:?}", "trace");
debug_time!("{:?}", "debug");
info_time!("measure function");
{
debug_time!("{:?}", "measuring block");
let mut sum = 0;
for el in 0..50000 {
sum += el;
}
println!("{:?}", sum);
}

print_time!("print");
error_time!("error_time");

trace_time!(target: "trace_time", "custom target");
debug_time!(target: "debug_time", "custom target");
info_time!(target: "info_time", "custom target");
error_time!(target: "measure_time", "custom target");
}
}

0 comments on commit bd82934

Please sign in to comment.