Class: Async::Clock

Inherits:
Object
  • Object
show all
Defined in:
lib/async/clock.rb

Overview

A convenient wrapper around the internal monotonic clock.

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(total = 0) ⇒ Clock

Create a new clock with the initial total time.



51
52
53
54
# File 'lib/async/clock.rb', line 51

def initialize(total = 0)
  @total = total
  @started = nil
end

Class Method Details

.measureObject

Measure the execution of a block of code.



35
36
37
38
39
40
41
# File 'lib/async/clock.rb', line 35

def self.measure
  start_time = self.now
  
  yield
  
  return self.now - start_time
end

.nowObject

Get the current elapsed monotonic time.



28
29
30
# File 'lib/async/clock.rb', line 28

def self.now
  ::Process.clock_gettime(::Process::CLOCK_MONOTONIC)
end

.startObject

Start measuring elapsed time from now.



45
46
47
# File 'lib/async/clock.rb', line 45

def self.start
  self.new.tap(&:start!)
end

Instance Method Details

#start!Object

Start measuring a duration.



57
58
59
# File 'lib/async/clock.rb', line 57

def start!
  @started ||= Clock.now
end

#stop!Object

Stop measuring a duration and append the duration to the current total.



62
63
64
65
66
67
68
69
# File 'lib/async/clock.rb', line 62

def stop!
  if @started
    @total += (Clock.now - @started)
    @started = nil
  end
  
  return @total
end

#totalObject

The total elapsed time including any current duration.



72
73
74
75
76
77
78
79
80
# File 'lib/async/clock.rb', line 72

def total
  total = @total
  
  if @started
    total += (Clock.now - @started)
  end
  
  return total
end