Class: Elapse::Stopwatch
- Inherits:
-
Object
- Object
- Elapse::Stopwatch
- Defined in:
- lib/elapse/stopwatch.rb
Overview
Our stopwatch class.
Instance Attribute Summary collapse
-
#started_at ⇒ Object
readonly
Returns the value of attribute started_at.
Instance Method Summary collapse
-
#clear ⇒ Object
Clear object.
-
#cumulative ⇒ Object
Stop the stopwatch and return cumulative time.
-
#initialize ⇒ Stopwatch
constructor
A new instance of Stopwatch.
-
#reset ⇒ Object
Reset stopwatch.
-
#running? ⇒ Boolean
Return true if the stopwatch is running.
-
#start ⇒ Object
Start the stopwatch.
-
#stop ⇒ Object
Stop the stopwatch.
-
#took ⇒ Object
Stop the stopwatch and return the last measurement.
Constructor Details
#initialize ⇒ Stopwatch
Returns a new instance of Stopwatch.
6 7 8 |
# File 'lib/elapse/stopwatch.rb', line 6 def initialize clear end |
Instance Attribute Details
#started_at ⇒ Object (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
#clear ⇒ Object
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 |
#cumulative ⇒ Object
Stop the stopwatch and return cumulative time.
19 20 21 22 |
# File 'lib/elapse/stopwatch.rb', line 19 def cumulative stop @cumulative end |
#reset ⇒ Object
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.
31 32 33 |
# File 'lib/elapse/stopwatch.rb', line 31 def running? !!@started_at end |
#start ⇒ Object
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 |
#stop ⇒ Object
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 |
#took ⇒ Object
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 |