Module: Blinkbox::CommonHelpers::TicToc

Defined in:
lib/blinkbox/tictoc.rb

Overview

Gives you two methods, `tic` and `toc`. Without arguments `toc` will give you the number of milliseconds since you last called `tic`. Takes one argument, which can be used to have two timers running independently:

@example: Basic use

include Blinkbox::CommonHelpers::TicToc
tic
sleep 9
p toc
# => 9001
# (It is over 9000 because time is an illusion, lunchtime doubly so)

@example: Parallel use

include Blinkbox::CommonHelpers::TicToc
tic :a
sleep 1
tic :b
sleep 1
p toc :b
# => 1000
sleep 1
p toc :a
# => 3000

Instance Method Summary collapse

Instance Method Details

#tic(label = :default) ⇒ Time?

Starts a timer with the given label. Will return the last value of the timer if #tic had been called before.

Parameters:

  • label (Symbol) (defaults to: :default)

    The label to use.

Returns:

  • (Time, nil)

    The Time #tic was called with this label previously


31
32
33
34
35
# File 'lib/blinkbox/tictoc.rb', line 31

def tic(label = :default)
  last_value = (@@timers ||= {})[label]
  @@timers[label] = Time.now.utc
  last_value
end

#tictoc_reset(labels = []) ⇒ nil

Resets the timer for a specific label, or all labels (if none are specified)

Parameters:

  • labels (Array<Symbol>) (defaults to: [])

    The labels to reset

Returns:

  • (nil)

51
52
53
54
55
56
57
# File 'lib/blinkbox/tictoc.rb', line 51

def tictoc_reset(labels = [])
  @@timers = {} if labels.empty?
  labels.each do |label|
    @@timers[label] = nil
  end
  nil
end

#toc(label = :default) ⇒ Float?

Returns the number of milliseconds since tic (for the same label) was called. Will return nil if tic has never been called.

Parameters:

  • label (Symbol) (defaults to: :default)

    The label to use.

Returns:

  • (Float, nil)

    The number of milliseconds since the equivalent #tic was last called.


42
43
44
45
# File 'lib/blinkbox/tictoc.rb', line 42

def toc(label = :default)
  return nil if @@timers[label].nil?
  ((Time.now.utc - @@timers[label]) * 1000).to_f
end