class Clock
A convenient wrapper around the internal monotonic clock.
Signature
- public
Since Async v1.
Definitions
def self.now
Get the current elapsed monotonic time.
Implementation
def self.now
::Process.clock_gettime(::Process::CLOCK_MONOTONIC)
end
def self.measure
Measure the execution of a block of code.
Signature
-
yields
{...} The block to execute.
-
returns
Numeric The total execution time.
Implementation
def self.measure
start_time = self.now
yield
return self.now - start_time
end
def self.start
Start measuring elapsed time from now.
Signature
-
returns
Clock
Implementation
def self.start
self.new.tap(&:start!)
end
def initialize(total = 0)
Create a new clock with the initial total time.
Signature
-
parameter
totalNumeric The initial clock duration.
Implementation
def initialize(total = 0)
@total = total
@started = nil
end
attr :started
Signature
-
returns
Numeric | Nil The time when the clock was started, or nil if not started.
def start!
Start measuring a duration.
Implementation
def start!
@started ||= Clock.now
end
def stop!
Stop measuring a duration and append the duration to the current total.
Implementation
def stop!
if @started
@total += (Clock.now - @started)
@started = nil
end
return @total
end
def total
The total elapsed time including any current duration.
Implementation
def total
total = @total
if @started
total += (Clock.now - @started)
end
return total
end
def reset!
Reset the total elapsed time. If the clock is currently running, reset the start time to now.
Implementation
def reset!
@total = 0
if @started
@started = Clock.now
end
end
def as_json(...)
Convert the clock to a JSON-compatible hash.
Signature
-
returns
Hash The JSON-compatible hash.
Implementation
def as_json(...)
{
started: self.started,
total: self.total,
}
end
def to_json(...)
Convert the clock to a JSON string.
Signature
-
returns
String The JSON string.
Implementation
def to_json(...)
self.as_json.to_json(...)
end