Class: Async::Clock

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

Overview

A convenient wrapper around the internal monotonic clock.

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

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

#startedObject (readonly)

Returns the value of attribute started.



41
42
43
# File 'lib/async/clock.rb', line 41

def started
  @started
end

Class Method Details

.measureObject

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

.nowObject

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

.startObject

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_jsonObject

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_jsonObject

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

#totalObject

The total elapsed time including any current duration.



59
60
61
62
63
64
65
66
67
# File 'lib/async/clock.rb', line 59

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