Class: DDMetrics::Stopwatch

Inherits:
Object
  • Object
show all
Defined in:
lib/ddmetrics/stopwatch.rb

Defined Under Namespace

Classes: AlreadyRunningError, NotRunningError, StillRunningError

Constant Summary collapse

NANOS_PER_SECOND =
1_000_000_000

Instance Method Summary collapse

Constructor Details

#initializeStopwatch

Returns a new instance of Stopwatch.



25
26
27
28
# File 'lib/ddmetrics/stopwatch.rb', line 25

def initialize
  @duration = 0
  @last_start = nil
end

Instance Method Details

#durationObject

Raises:



50
51
52
53
54
# File 'lib/ddmetrics/stopwatch.rb', line 50

def duration
  raise StillRunningError if running?

  @duration.to_f / NANOS_PER_SECOND
end

#runObject



30
31
32
33
34
35
# File 'lib/ddmetrics/stopwatch.rb', line 30

def run
  start
  yield
ensure
  stop
end

#running?Boolean

Returns:

  • (Boolean)


56
57
58
# File 'lib/ddmetrics/stopwatch.rb', line 56

def running?
  !@last_start.nil?
end

#startObject



37
38
39
40
41
# File 'lib/ddmetrics/stopwatch.rb', line 37

def start
  raise AlreadyRunningError if running?

  @last_start = nanos_now
end

#stopObject

Raises:



43
44
45
46
47
48
# File 'lib/ddmetrics/stopwatch.rb', line 43

def stop
  raise NotRunningError unless running?

  @duration += (nanos_now - @last_start)
  @last_start = nil
end

#stopped?Boolean

Returns:

  • (Boolean)


60
61
62
# File 'lib/ddmetrics/stopwatch.rb', line 60

def stopped?
  !running?
end