Timer
in package
Class Timer
A static utility class for tracking named execution timers with microsecond precision. Supports multiple concurrent timers, lap timing, UTC/local time modes, and comprehensive metrics collection. Integrates with Primordyx EventManager for timer lifecycle events.
Features:
- Named timer management with start/stop/restart functionality
- Lap timing for performance profiling within timer sessions
- Real-time elapsed time calculation for running timers
- Comprehensive metrics including longest/shortest timers and averages
- Event firing for timer lifecycle (started, stopped, removed, etc.)
- JSON export capabilities for timer data persistence
- Bulk operations on all running timers
Usage Examples:
Basic timer operations: Timer::start('api_call', 'Fetching user data from API'); // ... perform work ... $elapsed = Timer::stop('api_call'); echo Timer::summary('api_call'); // "[api_call] [Fetching user data from API] - 1.234s"
Lap timing for detailed profiling: Timer::start('database_batch'); Timer::lap('database_batch', 'Connected to DB'); // ... database operations ... Timer::lap('database_batch', 'Finished user queries'); // ... more operations ... Timer::stop('database_batch');
Metrics and analysis: $metrics = Timer::metrics(); echo "Total active timers: {$metrics['total']}"; echo "Average execution time: {$metrics['average_elapsed']}s";
Bulk operations: Timer::setLapOnAllRunning('Checkpoint 1'); Timer::stopAllRunning();
Tags
Table of Contents
Properties
- $debug : bool
- Controls debug mode for additional verbose timer information.
- $logging : bool
- Global flag to enable or disable timer activity logging.
- $timers : array<string, array{key: string, start: float, end: float|null, elapsed: float|null, description: string, running: int, laps: array}>
- Internal storage for all active and stopped timers, indexed by timer key.
- $useUtc : bool
- Controls whether time formatting uses UTC timezone.
Methods
- allRawJson() : string
- Export all timer data as pretty-printed JSON.
- asJson() : string|null
- Export a timer's complete data as formatted JSON.
- changeDescription() : void
- Update the description of an existing timer.
- clear() : void
- Remove all timers and reset the internal timer storage.
- debug() : bool
- Enable or disable debug mode for verbose timer information.
- description() : string|null
- Get the description text for a timer.
- elapsed() : int|null
- Get the current elapsed time for a timer in seconds.
- export() : void
- Export all timer data to a JSON file for persistence or analysis.
- fastestLap() : array<string|int, mixed>
- Find the fastest lap time across all timers and their lap data.
- getLaps() : array<string|int, mixed>
- Retrieve all lap data for a specific timer.
- getTimer() : array<string|int, mixed>
- Retrieve timer data by key, automatically creating the timer if it doesn't exist.
- has() : bool
- Check whether a timer with the specified key exists.
- lap() : float
- Add a lap marker to a running timer for performance profiling.
- logging() : bool
- Enable or disable logging of timer activity.
- longest() : array<string|int, mixed>|null
- Find the timer with the longest elapsed time.
- metrics() : array<string|int, mixed>
- Generate comprehensive metrics and statistics across all timers.
- peek() : array<string|int, mixed>|null
- Get the most recently created timer (LIFO - Last In, First Out).
- remove() : void
- Completely remove a timer from the internal storage.
- restart() : float
- Stop an existing timer and immediately restart it with a new description.
- restartAllRunning() : void
- Restart all currently running timers while preserving their descriptions.
- setLapOnAllRunning() : void
- Add a lap marker to all currently running timers.
- shortest() : array<string|int, mixed>|null
- Find the timer with the shortest elapsed time.
- start() : float
- Start a new timer with the specified key and optional description.
- status() : string|null
- Get the current operational status of a timer.
- stop() : float
- Stop a running timer and calculate its total elapsed time.
- stopAllRunning() : void
- Stop all currently running timers.
- stopAllWithLap() : void
- Add a final lap to all running timers and then stop them.
- summary() : string|null
- Generate a human-readable summary string for a timer.
- timersRaw() : array<string|int, mixed>
- Return the complete internal timers array without any processing.
- useUtc() : bool
- Get or set the UTC timezone formatting preference.
- getExtreme() : array<string|int, mixed>|null
- Internal utility method to find either the longest or shortest timer.
Properties
$debug
Controls debug mode for additional verbose timer information.
protected
static bool
$debug
= false
When enabled, provides more detailed logging and diagnostic information about timer operations. Used primarily during development and troubleshooting.
$logging
Global flag to enable or disable timer activity logging.
protected
static bool
$logging
= true
When enabled, timer operations may generate log entries or trigger additional diagnostic output. This is separate from the EventManager events that are always fired regardless of this setting.
$timers
Internal storage for all active and stopped timers, indexed by timer key.
protected
static array<string, array{key: string, start: float, end: float|null, elapsed: float|null, description: string, running: int, laps: array}>
$timers
= []
Each timer entry contains:
- 'key': string - The unique identifier for this timer
- 'start': float - Unix timestamp with microseconds when timer was started
- 'end': float|null - Unix timestamp with microseconds when timer was stopped (null if running)
- 'elapsed': float|null - Total elapsed seconds (null if still running)
- 'description': string - Human-readable description of what this timer tracks
- 'running': int - 1 if timer is active, 0 if stopped
- 'laps': array - Array of lap entries with 'label', 'timestamp', and 'elapsed' keys
$useUtc
Controls whether time formatting uses UTC timezone.
protected
static bool
$useUtc
= true
When true, all time formatting operations will use UTC timezone. When false, uses the system's local timezone for time display. This setting affects human-readable time output but does not impact the underlying timer calculations which always use Unix timestamps.
Methods
allRawJson()
Export all timer data as pretty-printed JSON.
public
static allRawJson() : string
Converts the complete internal timer storage to a formatted JSON string suitable for logging, debugging, or external analysis. Includes all timer data, lap times, and metadata.
Return values
string —Pretty-printed JSON representation of all timer data.
asJson()
Export a timer's complete data as formatted JSON.
public
static asJson(string $key) : string|null
Converts all timer data including timing information, description, and lap data into a pretty-printed JSON string suitable for logging, debugging, or persistence.
Parameters
- $key : string
-
The unique identifier of the timer.
Return values
string|null —Pretty-printed JSON representation of timer data, or null if timer doesn't exist.
changeDescription()
Update the description of an existing timer.
public
static changeDescription(string $key, string $description) : void
Allows changing the descriptive text associated with a timer without affecting its timing data. If the timer doesn't exist, it will be automatically created with the new description.
Fires 'timer.description.changing' and 'timer.description.changed' events.
Parameters
- $key : string
-
The unique identifier of the timer.
- $description : string
-
The new description text to assign.
Tags
clear()
Remove all timers and reset the internal timer storage.
public
static clear() : void
Permanently deletes all timer data including running and stopped timers. This operation cannot be undone and will clear all lap times and metrics.
Fires 'timer.cleared_all' event through EventManager before clearing.
debug()
Enable or disable debug mode for verbose timer information.
public
static debug([bool|null $on = null ]) : bool
Debug mode provides additional diagnostic information about timer operations. This method acts as both getter and setter, returning the previous state when making changes.
Parameters
- $on : bool|null = null
-
True to enable debug mode, false to disable, null to just get current state.
Return values
bool —The previous debug state before any changes were made.
description()
Get the description text for a timer.
public
static description(string $key) : string|null
Returns the human-readable description that was provided when the timer was created or last restarted. Useful for displaying timer purpose in logs or reports.
Parameters
- $key : string
-
The unique identifier of the timer.
Return values
string|null —The timer's description, or null if timer doesn't exist.
elapsed()
Get the current elapsed time for a timer in seconds.
public
static elapsed(string $key) : int|null
For running timers, calculates elapsed time from start to current time. For stopped timers, returns the final elapsed time that was calculated when stopped. If the timer doesn't exist, it will be automatically created first.
Parameters
- $key : string
-
The unique identifier of the timer.
Tags
Return values
int|null —Elapsed time in seconds, or null if calculation fails.
export()
Export all timer data to a JSON file for persistence or analysis.
public
static export(string $filename) : void
Writes the complete timer dataset to the specified file in pretty-printed JSON format. Useful for preserving timing data beyond the current process lifecycle or for external analysis tools.
Parameters
- $filename : string
-
Full path and filename where JSON data should be written.
Tags
fastestLap()
Find the fastest lap time across all timers and their lap data.
public
static fastestLap() : array<string|int, mixed>
Searches through all recorded laps in all timers to find the one with the shortest elapsed time. Useful for identifying the best performance among similar operations being timed across different timer instances.
Return values
array<string|int, mixed> —Associative array containing 'timer_key', 'label', 'elapsed', and 'elapsed_human' for the fastest lap, or empty array if no laps exist.
getLaps()
Retrieve all lap data for a specific timer.
public
static getLaps(string $key) : array<string|int, mixed>
Returns an array of all lap markers that have been recorded for the specified timer. Each lap entry contains the label, timestamp, and elapsed time from timer start.
Parameters
- $key : string
-
The unique identifier of the timer.
Return values
array<string|int, mixed> —Array of lap data, each containing 'label', 'timestamp', and 'elapsed' keys.
getTimer()
Retrieve timer data by key, automatically creating the timer if it doesn't exist.
public
static getTimer(string $key) : array<string|int, mixed>
This is a convenience method that ensures a timer exists before returning its data. If the requested timer doesn't exist, it will be automatically started with a default description indicating it was auto-created.
Parameters
- $key : string
-
The unique identifier for the timer.
Return values
array<string|int, mixed> —The complete timer data array containing all timer properties.
has()
Check whether a timer with the specified key exists.
public
static has(string $key) : bool
Returns true if a timer has been created with the given key, regardless of whether it's currently running or stopped. Returns false if no timer with that key has been created.
Parameters
- $key : string
-
The timer key to check for existence.
Tags
Return values
bool —True if the timer exists, false otherwise.
lap()
Add a lap marker to a running timer for performance profiling.
public
static lap(string $key[, string $label = '' ]) : float
Records an intermediate timing point within a timer's execution, useful for tracking performance of different phases within a longer operation. Each lap includes a timestamp and the elapsed time from the timer's start.
If the timer doesn't exist, it will be automatically created first. Fires 'timer.lap.set' event through EventManager with updated timer data.
Parameters
- $key : string
-
The unique identifier of the timer to add a lap to.
- $label : string = ''
-
Descriptive label for this lap (e.g., 'Database connected', 'Data processed').
Tags
Return values
float —The Unix timestamp when the lap was recorded.
logging()
Enable or disable logging of timer activity.
public
static logging([bool|null $on = null ]) : bool
This method acts as both a getter and setter. When called without parameters, it returns the current logging state. When called with a boolean parameter, it updates the logging state and returns the previous value.
Parameters
- $on : bool|null = null
-
True to enable logging, false to disable, null to just get current state.
Return values
bool —The previous logging state before any changes were made.
longest()
Find the timer with the longest elapsed time.
public
static longest([bool $includeRunningOnly = false ]) : array<string|int, mixed>|null
Searches through all timers to find the one with the greatest elapsed time. Can optionally be restricted to only running timers. For running timers, elapsed time is calculated from start to current time.
Parameters
- $includeRunningOnly : bool = false
-
If true, only considers currently running timers.
Return values
array<string|int, mixed>|null —Array containing 'key', 'description', 'elapsed', and 'elapsed_human', or null if no timers exist.
metrics()
Generate comprehensive metrics and statistics across all timers.
public
static metrics([bool $includeRunningOnly = false ]) : array<string|int, mixed>
Calculates aggregate statistics including timer counts, total elapsed time, averages, and identifies the longest and shortest timers. Useful for performance analysis and system monitoring.
Parameters
- $includeRunningOnly : bool = false
-
If true, calculations only include currently running timers.
Tags
Return values
array<string|int, mixed> —Comprehensive metrics array containing:
- 'total': Total number of timers included in calculations
- 'running': Number of currently running timers
- 'stopped': Number of stopped timers
- 'total_elapsed': Sum of all elapsed times in seconds
- 'average_elapsed': Average elapsed time in seconds
- 'longest': Array with details of longest timer (or null)
- 'shortest': Array with details of shortest timer (or null)
peek()
Get the most recently created timer (LIFO - Last In, First Out).
public
static peek() : array<string|int, mixed>|null
Returns the timer data for whichever timer was most recently added to the internal storage. Useful for stack-like timer management or when working with nested timing operations.
Return values
array<string|int, mixed>|null —Complete timer data array for the most recent timer, or null if no timers exist.
remove()
Completely remove a timer from the internal storage.
public
static remove(string $key) : void
Permanently deletes the timer and all its associated data including lap times and elapsed time information. This action cannot be undone.
Fires 'timer.removed' event through EventManager before deletion.
Parameters
- $key : string
-
The unique identifier of the timer to remove.
Tags
restart()
Stop an existing timer and immediately restart it with a new description.
public
static restart(string $key[, string $description = '' ]) : float
This is equivalent to calling stop() followed by start(), but maintains the timer's history and fires appropriate lifecycle events. Useful for resetting a timer while keeping the same key and updating its purpose.
Fires multiple events: 'timer.restarting', 'timer.stopped', 'timer.started', and 'timer.restarted'.
Parameters
- $key : string
-
The unique identifier of the timer to restart.
- $description : string = ''
-
New description for the restarted timer.
Tags
Return values
float —The Unix timestamp when the timer was restarted.
restartAllRunning()
Restart all currently running timers while preserving their descriptions.
public
static restartAllRunning() : void
Bulk operation that stops and immediately restarts every running timer, maintaining their original descriptions. Useful for synchronizing timing periods across multiple operations or resetting timing while keeping context.
Fires 'timer.restart_all_running' event before processing.
Tags
setLapOnAllRunning()
Add a lap marker to all currently running timers.
public
static setLapOnAllRunning([string $label = '' ]) : void
Convenient bulk operation that applies the same lap label to every timer that is currently in a running state. Useful for marking synchronization points across multiple concurrent operations.
Fires 'timer.set_lap_on_all_running' event before processing.
Parameters
- $label : string = ''
-
Descriptive label to apply to each lap.
Tags
shortest()
Find the timer with the shortest elapsed time.
public
static shortest([bool $includeRunningOnly = false ]) : array<string|int, mixed>|null
Searches through all timers to find the one with the least elapsed time. Can optionally be restricted to only running timers. For running timers, elapsed time is calculated from start to current time.
Parameters
- $includeRunningOnly : bool = false
-
If true, only considers currently running timers.
Return values
array<string|int, mixed>|null —Array containing 'key', 'description', 'elapsed', and 'elapsed_human', or null if no timers exist.
start()
Start a new timer with the specified key and optional description.
public
static start(string $key[, string $description = '' ]) : float
Creates a new timer entry and begins timing immediately. If a timer with the same key already exists, it will be overwritten. The timer starts in a "running" state and will continue until explicitly stopped.
Fires 'timer.started' event through EventManager with the timer data.
Parameters
- $key : string
-
Unique identifier for this timer (e.g., 'api_call', 'database_query').
- $description : string = ''
-
Human-readable description of what this timer tracks.
Return values
float —The Unix timestamp (with microseconds) when the timer was started.
status()
Get the current operational status of a timer.
public
static status(string $key) : string|null
Returns a string indicating whether the timer is currently running or has been stopped. Useful for conditional logic based on timer state.
Parameters
- $key : string
-
The unique identifier of the timer.
Return values
string|null —'running' if timer is active, 'stopped' if timer has been stopped, null if timer doesn't exist.
stop()
Stop a running timer and calculate its total elapsed time.
public
static stop(string $key) : float
Marks the timer as stopped, records the end timestamp, and calculates the total elapsed time in seconds. If the timer doesn't exist, it will be automatically created first (with a default description) and then immediately stopped.
Fires 'timer.stopped' event through EventManager with the final timer data.
Parameters
- $key : string
-
The unique identifier of the timer to stop.
Return values
float —Total elapsed time in seconds (with microsecond precision).
stopAllRunning()
Stop all currently running timers.
public
static stopAllRunning() : void
Iterates through all active timers and stops each one that is currently running. Stopped timers are left unchanged. This is useful for bulk cleanup operations or when shutting down a process.
Fires 'timer.stopping_all_running' event before stopping any timers.
Tags
stopAllWithLap()
Add a final lap to all running timers and then stop them.
public
static stopAllWithLap([string $lapLabel = 'Final lap' ]) : void
Bulk operation that first adds a lap marker (typically labeled as "Final lap") to all running timers, then stops each of them. Useful for graceful shutdown or end-of-process timing collection.
Fires 'timer.stopping_all_with_laps' event before processing.
Parameters
- $lapLabel : string = 'Final lap'
-
Label for the final lap added to each timer before stopping.
Tags
summary()
Generate a human-readable summary string for a timer.
public
static summary(string $key) : string|null
Creates a concise, formatted string showing the timer key, description (if present), and elapsed time in human-readable format. Perfect for logging or display purposes.
Format: "[timer_key] [description] - elapsed_time" Example: "[api_call] [Fetching user data] - 1.234s"
Parameters
- $key : string
-
The unique identifier of the timer.
Return values
string|null —Formatted summary string, or null if timer doesn't exist.
timersRaw()
Return the complete internal timers array without any processing.
public
static timersRaw() : array<string|int, mixed>
Provides direct access to the raw timer storage for advanced use cases, debugging, or when you need to inspect the exact internal timer structure. Use with caution as direct manipulation of this data could break timer consistency.
Return values
array<string|int, mixed> —The complete internal timers array with all timer data.
useUtc()
Get or set the UTC timezone formatting preference.
public
static useUtc([bool|null $on = null ]) : bool
Controls whether human-readable time formatting uses UTC or local timezone. Does not affect the underlying timer calculations which always use Unix timestamps.
Parameters
- $on : bool|null = null
-
True for UTC formatting, false for local timezone, null to just get current state.
Return values
bool —The current UTC formatting state (before any changes if setting).
getExtreme()
Internal utility method to find either the longest or shortest timer.
private
static getExtreme(bool $includeRunningOnly, string $mode) : array<string|int, mixed>|null
Searches through all timers (or just running ones) to find the extreme value based on elapsed time. Used by the longest() and shortest() public methods.
Parameters
- $includeRunningOnly : bool
-
If true, only considers currently running timers.
- $mode : string
-
Either 'longest' or 'shortest' to determine which extreme to find.
Return values
array<string|int, mixed>|null —Array with 'key', 'description', 'elapsed', and 'elapsed_human' keys, or null if no timers match criteria.