Class: Async::Clock
- Inherits:
-
Object
- Object
- Async::Clock
- Defined in:
- lib/async/clock.rb
Overview
A convenient wrapper around the internal monotonic clock.
Instance Attribute Summary collapse
-
#started ⇒ Object
readonly
Returns the value of attribute started.
Class Method Summary collapse
-
.measure ⇒ Object
Measure the execution of a block of code.
-
.now ⇒ Object
Get the current elapsed monotonic time.
-
.start ⇒ Object
Start measuring elapsed time from now.
Instance Method Summary collapse
-
#as_json ⇒ Object
Convert the clock to a JSON-compatible hash.
-
#initialize(total = 0) ⇒ Clock
constructor
Create a new clock with the initial total time.
-
#reset! ⇒ Object
Reset the total elapsed time.
-
#start! ⇒ Object
Start measuring a duration.
-
#stop! ⇒ Object
Stop measuring a duration and append the duration to the current total.
-
#to_json ⇒ Object
Convert the clock to a JSON string.
-
#total ⇒ Object
The total elapsed time including any current duration.
Constructor Details
#initialize(total = 0) ⇒ Clock
Create a new clock with the initial total time.
35 36 37 38 |
# File 'lib/async/clock.rb', line 35 def initialize(total = 0) @total = total @started = nil end |
Instance Attribute Details
#started ⇒ Object (readonly)
Returns the value of attribute started.
41 42 43 |
# File 'lib/async/clock.rb', line 41 def started @started end |
Class Method Details
.measure ⇒ Object
Measure the execution of a block of code.
19 20 21 22 23 24 25 |
# File 'lib/async/clock.rb', line 19 def self.measure start_time = self.now yield return self.now - start_time end |
.now ⇒ Object
Get the current elapsed monotonic time.
12 13 14 |
# File 'lib/async/clock.rb', line 12 def self.now ::Process.clock_gettime(::Process::CLOCK_MONOTONIC) end |
.start ⇒ Object
Start measuring elapsed time from now.
29 30 31 |
# File 'lib/async/clock.rb', line 29 def self.start self.new.tap(&:start!) end |
Instance Method Details
#as_json ⇒ Object
Convert the clock to a JSON-compatible hash.
81 82 83 84 85 86 |
# File 'lib/async/clock.rb', line 81 def as_json(...) { started: self.started, total: self.total, } end |
#reset! ⇒ Object
Reset the total elapsed time. If the clock is currently running, reset the start time to now.
70 71 72 73 74 75 76 |
# File 'lib/async/clock.rb', line 70 def reset! @total = 0 if @started @started = Clock.now end end |
#start! ⇒ Object
Start measuring a duration.
44 45 46 |
# File 'lib/async/clock.rb', line 44 def start! @started ||= Clock.now end |
#stop! ⇒ Object
Stop measuring a duration and append the duration to the current total.
49 50 51 52 53 54 55 56 |
# File 'lib/async/clock.rb', line 49 def stop! if @started @total += (Clock.now - @started) @started = nil end return @total end |
#to_json ⇒ Object
Convert the clock to a JSON string.
91 92 93 |
# File 'lib/async/clock.rb', line 91 def to_json(...) self.as_json.to_json(...) end |