Class: Philiprehberger::Metric::Timer
- Inherits:
-
Object
- Object
- Philiprehberger::Metric::Timer
- Defined in:
- lib/philiprehberger/metric/timer.rb
Overview
A scoped timer that measures elapsed time between construction and an explicit stop.
Provides an alternative to the block-based Registry#time helper for flows where a block is awkward (for example, when the start and stop occur in different methods or across callback boundaries).
Instance Method Summary collapse
-
#elapsed ⇒ Float
Return the elapsed seconds since construction without stopping the timer.
-
#initialize(histogram_name, registry: Philiprehberger::Metric.default_registry) ⇒ Timer
constructor
Create a new timer and capture the start time.
-
#reset ⇒ void
Reset the timer, clearing the stopped state.
-
#stop(labels: {}) ⇒ Float
Stop the timer and record the elapsed seconds into the target histogram.
Constructor Details
#initialize(histogram_name, registry: Philiprehberger::Metric.default_registry) ⇒ Timer
Create a new timer and capture the start time.
21 22 23 24 25 26 27 28 |
# File 'lib/philiprehberger/metric/timer.rb', line 21 def initialize(histogram_name, registry: Philiprehberger::Metric.default_registry) @histogram_name = histogram_name @registry = registry @start = monotonic_now @stopped_at = nil @recorded_elapsed = nil @reset = false end |
Instance Method Details
#elapsed ⇒ Float
Return the elapsed seconds since construction without stopping the timer.
If the timer has already been stopped, returns the elapsed value captured at stop time.
56 57 58 59 60 |
# File 'lib/philiprehberger/metric/timer.rb', line 56 def elapsed return @recorded_elapsed if @stopped_at monotonic_now - @start end |
#reset ⇒ void
This method returns an undefined value.
Reset the timer, clearing the stopped state.
After reset, #stop will raise — the timer must be re-constructed for a fresh measurement. Use reset primarily as a way to discard a running timer without recording an observation.
69 70 71 72 73 74 |
# File 'lib/philiprehberger/metric/timer.rb', line 69 def reset @start = monotonic_now @stopped_at = nil @recorded_elapsed = nil @reset = true end |
#stop(labels: {}) ⇒ Float
Stop the timer and record the elapsed seconds into the target histogram.
Idempotent: subsequent calls return the cached elapsed value from the first stop without recording an additional observation. After an explicit #reset, calling #stop raises Error — reset leaves the timer in a state that cannot be stopped again without re-constructing the timer.
40 41 42 43 44 45 46 47 48 |
# File 'lib/philiprehberger/metric/timer.rb', line 40 def stop(labels: {}) raise Error, 'Timer has been reset; cannot stop a reset timer' if @reset return @recorded_elapsed if @stopped_at elapsed = monotonic_now - @start @registry.observe(@histogram_name, elapsed, labels: labels) @stopped_at = monotonic_now @recorded_elapsed = elapsed end |