timer.py

Overview

The timer.py file provides a lightweight utility for measuring elapsed time of tasks or code blocks with millisecond precision. It consists primarily of the TaskTimer class, which supports starting, stopping, resetting, and retrieving elapsed time. This utility is designed to handle typical edge cases gracefully, such as preventing multiple starts from resetting the timer and returning zero elapsed time if stopped before starting.

The file also includes the now_ts() function, a wrapper around the system clock retrieval function to obtain the current epoch time in seconds as a floating-point value. This abstraction facilitates easier testing and potential future adaptations of the time source.

This file implements core functionality related to the Precise Task Timing topic and the Timer Operations subtopic by managing timer state and elapsed time calculations reliably.


Classes and Functions

Function: now_ts()

def now_ts() -> float:
current_time = now_ts()
print(f"Current time (epoch seconds): {current_time}")

Class: TaskTimer

@dataclass
class TaskTimer:

A simple timer class to measure elapsed time of tasks with millisecond precision.

Attributes:

Methods:

start() -> TaskTimer

Starts the timer. If the timer is already running, this method does nothing (idempotent).

timer = TaskTimer().start()
stop() -> TaskTimer

Stops the timer. If the timer is not running (never started or already stopped), does nothing.

timer.stop()
elapsed_ms (property) -> int

Calculates and returns the elapsed time in milliseconds.

print(timer.elapsed_ms)  # e.g., 1234
reset() -> None

Resets the timer state by clearing start and stop timestamps and setting _running to False.

timer.reset()

Implementation Details and Algorithms


Interaction with Other Parts of the System


Visual Diagram: Class Structure of TaskTimer

classDiagram
class TaskTimer {
+started_at: Optional[float]
+stopped_at: Optional[float]
-_running: bool
+start()
+stop()
+elapsed_ms
+reset()
}
class now_ts {
+now_ts()
}

This class diagram shows the TaskTimer class with its main attributes and methods, alongside the standalone now_ts function that supplies the current time. The private _running attribute manages the timer's active state internally.


Usage Example

from timer import TaskTimer

# Create and start the timer
timer = TaskTimer().start()

# Perform some work here
# ...

# Stop the timer
timer.stop()

# Retrieve elapsed time in milliseconds
print(f"Elapsed time: {timer.elapsed_ms} ms")

# Reset the timer for reuse
timer.reset()

This example demonstrates the typical lifecycle of using TaskTimer to measure elapsed time for a code segment.


For deeper understanding of timing mechanisms, see the Timer Operations subtopic. To learn about time retrieval abstraction, refer to Current Time Utility. For practical usage patterns, consult Timer Usage Demo.