Class: Elapse::Stopwatch

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

Overview

Our stopwatch class.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeStopwatch

Returns a new instance of Stopwatch.



6
7
8
# File 'lib/elapse/stopwatch.rb', line 6

def initialize
  clear
end

Instance Attribute Details

#started_atObject (readonly)

Returns the value of attribute started_at.



4
5
6
# File 'lib/elapse/stopwatch.rb', line 4

def started_at
  @started_at
end

Instance Method Details

#clearObject

Clear object.



11
12
13
14
15
16
# File 'lib/elapse/stopwatch.rb', line 11

def clear
  @cumulative = nil
  @started_at = nil
  @took = nil
  self    # By convention.
end

#cumulativeObject

Stop the stopwatch and return cumulative time.



19
20
21
22
# File 'lib/elapse/stopwatch.rb', line 19

def cumulative
  stop
  @cumulative
end

#resetObject

Reset stopwatch.



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

def reset
  clear
  nil
end

#running?Boolean

Return true if the stopwatch is running.

Returns:

  • (Boolean)


31
32
33
# File 'lib/elapse/stopwatch.rb', line 31

def running?
  !!@started_at
end

#startObject

Start the stopwatch. Return Time::now.



36
37
38
39
# File 'lib/elapse/stopwatch.rb', line 36

def start
  raise "Stopwatch already started" if @started_at
  @started_at = Time.now
end

#stopObject

Stop the stopwatch. Return Time::now.



42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/elapse/stopwatch.rb', line 42

def stop
  now = Time.now

  # We can stop multiple times. We cannot stop if never started.
  if @started_at
    @cumulative ||= 0.0
    @took = now - @started_at
    @cumulative += @took
    @started_at = nil
  elsif not @cumulative
    raise "Stopwatch was never started"
  end

  now
end

#tookObject

Stop the stopwatch and return the last measurement.

start
sleep 0.1
took      # => 0.100393978


63
64
65
66
# File 'lib/elapse/stopwatch.rb', line 63

def took
  stop
  @took
end