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:
Purpose:
Returns the current epoch time in seconds as a float. Encapsulates the system time retrieval (time.time()) to allow easier testing and potential future modification of the time source.Returns:
float— Current time in seconds since the epoch.Usage Example:
current_time = now_ts()
print(f"Current time (epoch seconds): {current_time}")
Notes:
This function is used internally by theTaskTimerclass to fetch timestamps for start, stop, and elapsed time calculations.
Class: TaskTimer
@dataclass
class TaskTimer:
A simple timer class to measure elapsed time of tasks with millisecond precision.
Attributes:
started_at: Optional[float]
Timestamp (epoch seconds) when the timer was started.Noneif never started or after reset.stopped_at: Optional[float]
Timestamp (epoch seconds) when the timer was stopped.Noneif currently running or after reset._running: bool(private)
Internal flag indicating whether the timer is currently running.
Methods:
start() -> TaskTimer
Starts the timer. If the timer is already running, this method does nothing (idempotent).
Returns:
self— allows method chaining.Behavior:
Records the current time vianow_ts()asstarted_atonly if not already running. Sets_runningtoTrue.Example:
timer = TaskTimer().start()
stop() -> TaskTimer
Stops the timer. If the timer is not running (never started or already stopped), does nothing.
Returns:
self— allows method chaining.Behavior:
Records the current time asstopped_atand sets_runningtoFalseonly if the timer was running.Example:
timer.stop()
elapsed_ms (property) -> int
Calculates and returns the elapsed time in milliseconds.
Returns:
int— elapsed time in milliseconds.Behavior:
If never started (
started_atisNone), returns 0.If running (not stopped), calculates elapsed time as
(current_time - started_at) * 1000.If stopped, calculates elapsed time as
(stopped_at - started_at) * 1000.Ensures elapsed time is always non-negative.
Example:
print(timer.elapsed_ms) # e.g., 1234
reset() -> None
Resets the timer state by clearing start and stop timestamps and setting _running to False.
Behavior:
After reset, the timer behaves as if newly created.Example:
timer.reset()
Implementation Details and Algorithms
The timer maintains internal timestamps (
started_at,stopped_at) and a_runningflag to track its state.The
start()method is idempotent; repeated calls do not reset the timer or affect the original start time.The
stop()method records the stop time only when the timer is running. If called beforestart(), elapsed time will be zero.The
elapsed_msproperty dynamically computes the elapsed time based on whether the timer is running or stopped, using current time or stored stop time accordingly.The use of the
@dataclassdecorator simplifies state management and initialization.The
now_ts()function abstracts the system time to facilitate testing and possible mocking.
Interaction with Other Parts of the System
This file is a core utility module for precise timing, used by higher-level components that require task duration measurement.
It is integrated within the system via the timer API exposed in the package's
init.py, enabling usage across different modules.The
TaskTimerclass is often used in conjunction with scheduling modules (see Cron Schedule Parsing and Next Run Calculation) in practical scenarios demonstrated by Timer Usage Demo.The timing source abstraction (
now_ts()) allows consistent time retrieval and simplifies unit testing by permitting the substitution of time values.
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.