Class: CodeTimer

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

Defined Under Namespace

Classes: NotTimingError

Instance Method Summary collapse

Constructor Details

#initializeCodeTimer

Returns a new instance of CodeTimer.



5
6
7
8
# File 'lib/code_timer.rb', line 5

def initialize
  @sections = {}
  @timing   = nil
end

Instance Method Details

#beginObject



10
11
12
# File 'lib/code_timer.rb', line 10

def begin
  initialize
end

#endObject



14
15
16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/code_timer.rb', line 14

def end
  stop if @timing

  total  = @sections.map {|k, v| v}.reduce(:+)
  output = ""

  output += "Total Time: #{total}s\n"

  @sections.each do |k, v|
    output += "#{k}:\t #{(v / total.to_f * 100).to_i}% / #{v}s\n"
  end

  output
end

#start(section) ⇒ Object

Raises:

  • (ArgumentError)


29
30
31
32
33
34
35
# File 'lib/code_timer.rb', line 29

def start(section)
  raise ArgumentError if section.nil? || section.empty?
  stop if @timing

  @sections[section] = Time.now.to_i
  @timing            = section
end

#stopObject

Raises:



37
38
39
40
41
# File 'lib/code_timer.rb', line 37

def stop
  raise NotTimingError unless @timing

  @sections[@timing] = Time.now.to_i - @sections[@timing]
end