File: timer.rb

package info (click to toggle)
ruby-cabin 0.9.1-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 272 kB
  • sloc: ruby: 1,306; makefile: 12
file content (39 lines) | stat: -rw-r--r-- 893 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
require "cabin/namespace"
require "cabin/metrics/histogram"

class Cabin::Metrics::Timer < Cabin::Metrics::Histogram
  # Start timing something.
  #
  # If no block is given
  # If a block is given, the execution of that block is timed.
  #
  public
  def time(&block)
    return time_block(&block) if block_given?

    # Return an object we can .stop
    # Call record(...) when we stop.
    return TimerContext.new { |duration| record(duration) }
  end # def time

  private
  def time_block(&block)
    start = Time.now
    block.call
    record(Time.now - start)
  end # def time_block

  class TimerContext
    public
    def initialize(&stop_callback)
      @start = Time.now
      @callback = stop_callback
    end

    public
    def stop
      duration = Time.now - @start
      @callback.call(duration)
    end # def stop
  end # class TimerContext
end # class Cabin::Metrics::Timer