1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362
//! # Tea Timer
//!
//! Tea Timer is a simple and efficient Rust library for measuring and reporting the duration of tasks. It provides an easy-to-use API for creating timers, measuring elapsed time, and formatting durations.
//!
//! ## Features
//!
//! - Create named timers
//! - Measure elapsed time
//! - Format durations in a human-readable format
//! - Restart timers with new task names
//! - Optional logging support using the `log` crate
//!
//! ## Installation
//!
//! Add this to your `Cargo.toml`:
//!
//! ```toml
//! tea-timer = "0.1.0"
//! ```
//!
//! ## Usage
//!
//! ### Macro Usage
//! ```rust
//!
//! let result = tea_timer::took! {
//! // ...any code
//! };
//! // this will print elapsed time and get result of thecode block
//! ```
//!
//! ### Function Usage
//! ```rust
//! use tea_timer::took;
//!
//! let result = took(|| {
//! // ...any code
//! }, "task");
//! // this will print elapsed time and get result of the function
//! ```
//!
//! ### Basic Usage
//! ```rust
//! use tea_timer::Timer;
//! use std::thread::sleep;
//! use std::time::Duration;
//!
//! let mut timer = Timer::new("task");
//! // Simulate some work with a sleep
//! sleep(Duration::from_secs(2));
//! // this will print elapsed time
//! timer.elapsed();
//! // Restart the timer with a new task name
//! timer.restart("new_task");
//! // Simulate more work
//! sleep(Duration::from_millis(500));
//! // Measure elapsed time again
//! // consume timer and print elapsed time
//! timer.stop();
//! ```
//!
//! ### Logging Usage
//! ```rust
//! use tea_timer::Timer;
//! use std::thread::sleep;
//! use std::time::Duration;
//!
//! let mut timer = Timer::new("task");
//! timer.log(); // This will log the elapsed time using the log crate
//! ```
mod display;
use std::time::Instant;
/// A struct for measuring and reporting the duration of tasks.
///
/// # Examples
///
/// ```
/// use tea_timer::Timer;
/// use std::thread::sleep;
/// use std::time::Duration;
///
/// let timer = Timer::new("Some Task");
/// sleep(Duration::from_millis(100));
/// timer.stop(); // This will print the duration of the task
/// ```
pub struct Timer {
pub start_time: Instant,
pub task_name: String,
}
impl Default for Timer {
#[inline]
fn default() -> Self {
Timer::new("")
}
}
impl std::fmt::Debug for Timer {
#[inline]
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.elapsed_str())
}
}
impl std::fmt::Display for Timer {
#[inline]
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.elapsed_str())
}
}
impl Timer {
/// Creates a new `Timer` instance with the given task name.
///
/// # Examples
///
/// ```
/// use tea_timer::Timer;
///
/// let timer = Timer::new("My Task");
/// assert_eq!(timer.task_name, "My Task");
/// ```
#[inline]
pub fn new(task_name: &str) -> Self {
Timer {
start_time: Instant::now(),
task_name: task_name.to_string(),
}
}
/// Restarts the timer with a new task name.
///
/// # Examples
///
/// ```
/// use tea_timer::Timer;
///
/// let mut timer = Timer::new("Task 1");
/// // Do some work...
/// timer.restart("Task 2");
/// assert_eq!(timer.task_name, "Task 2");
/// // Timer now measures a new task
/// ```
#[inline]
pub fn restart(&mut self, task_name: &str) {
self.start_time = Instant::now();
self.task_name = task_name.to_string();
}
/// Returns the duration elapsed since the timer started.
///
/// # Examples
///
/// ```
/// use tea_timer::Timer;
/// use std::thread::sleep;
/// use std::time::Duration;
///
/// let timer = Timer::new("Test Task");
/// sleep(Duration::from_millis(10));
/// assert!(timer.duration().as_millis() >= 10);
/// ```
#[inline]
pub fn duration(&self) -> std::time::Duration {
self.start_time.elapsed()
}
/// Returns a formatted string representation of the elapsed duration.
///
/// # Examples
///
/// ```
/// use tea_timer::Timer;
/// use std::thread::sleep;
/// use std::time::Duration;
///
/// let timer = Timer::new("Test Task");
/// sleep(Duration::from_millis(10));
/// assert!(timer.duration_str().contains("ms"));
/// ```
#[inline]
pub fn duration_str(&self) -> String {
display::format_duration(self.duration())
}
#[inline]
pub fn elapsed_str(&self) -> String {
format!("{} elapsed {}", self.task_name, self.duration_str())
}
#[inline]
pub fn took_str(&self) -> String {
format!("{} took {}", self.task_name, self.duration_str())
}
/// Prints the elapsed time for the task.
///
/// # Examples
///
/// ```
/// use tea_timer::Timer;
/// use std::thread::sleep;
/// use std::time::Duration;
///
/// let timer = Timer::new("Test Task");
/// sleep(Duration::from_millis(10));
/// timer.elapsed(); // This will print to stdout
/// ```
#[inline]
pub fn elapsed(&self) {
println!("{}", self.elapsed_str());
}
/// Stops the timer and prints the duration of the task.
///
/// # Examples
///
/// ```
/// use tea_timer::Timer;
/// use std::thread::sleep;
/// use std::time::Duration;
///
/// let timer = Timer::new("Sleep Task");
/// sleep(Duration::from_millis(100));
/// timer.stop(); // This will print: "Sleep Task took 100.00ms" (approximately)
/// ```
#[inline]
pub fn stop(self) {
println!("{}", self.took_str());
}
/// Logs the elapsed time using the `log` crate.
///
/// This method is only available when the `log` feature is enabled.
///
/// # Examples
///
/// ```
/// # #[cfg(feature = "log")]
/// # {
/// use tea_timer::Timer;
/// use std::thread::sleep;
/// use std::time::Duration;
///
/// let timer = Timer::new("Log Task");
/// sleep(Duration::from_millis(10));
/// timer.log(); // This will log using the log crate
/// # }
/// ```
#[inline]
#[cfg(feature = "log")]
pub fn log(&self) {
log::info!("{}", self.elapsed_str());
}
}
#[inline]
pub fn took<F: FnOnce() -> R, R>(f: F, task_name: &str) -> R {
let timer = Timer::new(task_name);
let result = f();
timer.stop();
result
}
#[inline]
pub fn ltook<F: FnOnce() -> R, R>(f: F, task_name: &str) -> R {
let timer = Timer::new(task_name);
let result = f();
timer.log();
result
}
#[macro_export]
macro_rules! took {
($($tt:tt)*) => {
{
let timer = $crate::Timer::new("");
let res = {$($tt)*};
timer.stop();
res
}
};
}
#[macro_export]
macro_rules! ltook {
($($tt:tt)*) => {
{
let timer = $crate::Timer::new("");
let res = {$($tt)*};
timer.log();
res
}
};
}
#[cfg(test)]
mod tests {
use super::*;
use std::thread::sleep;
use std::time::Duration;
#[test]
fn test_timer_new() {
let timer = Timer::new("Test Task");
assert_eq!(timer.task_name, "Test Task");
}
#[test]
fn test_timer_restart() {
let mut timer = Timer::new("Task 1");
timer.restart("Task 2");
assert_eq!(timer.task_name, "Task 2");
}
#[test]
fn test_timer_duration() {
let timer = Timer::new("Duration Test");
sleep(Duration::from_millis(10));
assert!(timer.duration().as_millis() >= 10);
}
#[test]
fn test_timer_duration_str() {
let timer = Timer::new("Duration Str Test");
sleep(Duration::from_millis(10));
assert!(timer.duration_str().contains("ms"));
}
#[test]
fn test_timer_default() {
let timer = Timer::default();
assert_eq!(timer.task_name, "");
}
#[test]
fn test_took() {
let result = took(
|| {
sleep(Duration::from_millis(10));
42
},
"Test Task",
);
assert_eq!(result, 42);
}
#[test]
fn test_took_macro() {
let result = took! {
sleep(Duration::from_millis(10));
42
};
assert_eq!(result, 42);
}
// Note: We can't easily test the `stop` method as it prints to stdout.
// In a real-world scenario, we might want to refactor to return the duration
// instead of printing it, which would make it more testable.
}