Class: Spectator::Timer
- Inherits:
-
Object
- Object
- Spectator::Timer
- Defined in:
- lib/spectator/timer.rb
Overview
The class Timer is intended to track a large number of short running events. Example would be something like an http request. Though “short running” is a bit subjective the assumption is that it should be under a minute.
Instance Method Summary collapse
-
#count ⇒ Object
Get the number of events recorded.
-
#initialize(id, clock = SystemClock.new) ⇒ Timer
constructor
A new instance of Timer.
-
#measure ⇒ Object
Measure this timer.
-
#record(nanos) ⇒ Object
Update the statistics kept by this timer.
-
#time ⇒ Object
Record the time it takes to execute the given block.
-
#total_time ⇒ Object
Get the total time of events recorded in nanoseconds.
Constructor Details
#initialize(id, clock = SystemClock.new) ⇒ Timer
Returns a new instance of Timer.
10 11 12 13 14 15 16 17 18 |
# File 'lib/spectator/timer.rb', line 10 def initialize(id, clock = SystemClock.new) @id = id @clock = clock @count = AtomicNumber.new(0) @total_time = AtomicNumber.new(0) @total_sq = AtomicNumber.new(0) @max = AtomicNumber.new(Float::NAN) end |
Instance Method Details
#count ⇒ Object
Get the number of events recorded
40 41 42 |
# File 'lib/spectator/timer.rb', line 40 def count @count.get end |
#measure ⇒ Object
Measure this timer. It returns the count, totalTime in seconds, max in seconds, and totalOfSquares (normalized) to seconds to seconds
51 52 53 54 55 56 57 58 59 60 61 62 |
# File 'lib/spectator/timer.rb', line 51 def measure total_seconds = @total_time.get_and_set(0) / 1e9 max_seconds = @max.get_and_set(Float::NAN) / 1e9 tot_sq_seconds = @total_sq.get_and_set(0) / 1e18 cnt = Measure.new(@id.with_stat('count'), @count.get_and_set(0)) tot = Measure.new(@id.with_stat('totalTime'), total_seconds) tot_sq = Measure.new(@id.with_stat('totalOfSquares'), tot_sq_seconds) mx = Measure.new(@id.with_stat('max'), max_seconds) [cnt, tot, tot_sq, mx] end |
#record(nanos) ⇒ Object
Update the statistics kept by this timer. If the amount of nanoseconds passed is negative, the value will be ignored.
22 23 24 25 26 27 28 |
# File 'lib/spectator/timer.rb', line 22 def record(nanos) return if nanos < 0 @count.add_and_get(1) @total_time.add_and_get(nanos) @total_sq.add_and_get(nanos * nanos) @max.max(nanos) end |
#time ⇒ Object
Record the time it takes to execute the given block
32 33 34 35 36 37 |
# File 'lib/spectator/timer.rb', line 32 def time start = @clock.monotonic_time yield elapsed = @clock.monotonic_time - start record(elapsed) end |
#total_time ⇒ Object
Get the total time of events recorded in nanoseconds
45 46 47 |
# File 'lib/spectator/timer.rb', line 45 def total_time @total_time.get end |