Class: StopWatch

Inherits:
Object
  • Object
show all
Defined in:
lib/spinning_cursor/stop_watch.rb

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.measure(&block) ⇒ Object

Instantiate class and call #measure



6
7
8
9
# File 'lib/spinning_cursor/stop_watch.rb', line 6

def self.measure(&block)
  sw = self.new
  sw.measure &block
end

Instance Method Details

#elapsed_timeObject

Note:

If the timer has not yet stopped, the time elapsed from the start of the timer till Time.now is returned

Returns the elapsed time



53
54
55
56
# File 'lib/spinning_cursor/stop_watch.rb', line 53

def elapsed_time
  time_now = Time.now
  (@stop_time || time_now ) - (@start_time || time_now)
end

#inspectObject



60
61
62
# File 'lib/spinning_cursor/stop_watch.rb', line 60

def inspect
  puts "#{old_inspect} #{{:elapsed_time => elapsed_time}}"
end

#measure(&block) ⇒ Object

Measures the time taken to process the passed block and returns the measurment (see #timing)



15
16
17
18
19
20
# File 'lib/spinning_cursor/stop_watch.rb', line 15

def measure(&block)
  start
  yield
  stop
  timing
end

#old_inspectObject



58
# File 'lib/spinning_cursor/stop_watch.rb', line 58

alias old_inspect inspect

#resetObject

Resets timer



44
45
46
# File 'lib/spinning_cursor/stop_watch.rb', line 44

def reset
  @start_time = @stop_time = nil
end

#startObject

Starts timer



25
26
27
28
29
# File 'lib/spinning_cursor/stop_watch.rb', line 25

def start
  @start_time = Time.now
  @stop_time = nil
  self
end

#stopObject

Stops timer



34
35
36
37
38
39
# File 'lib/spinning_cursor/stop_watch.rb', line 34

def stop
  if @start_time
    @stop_time = Time.now
  end
  self
end

#timingObject

Returns the measurement in a hash containing

  • the start time
  • the stop time
  • the total elapsed time


70
71
72
73
74
# File 'lib/spinning_cursor/stop_watch.rb', line 70

def timing
  { :start_time   => @start_time,
    :stop_time    => @stop_time,
    :elapsed_time => elapsed_time }
end