Class: Tap::Middlewares::Profiler

Inherits:
Tap::Middleware
  • Object
show all
Defined in:
lib/tap/middlewares/profiler.rb

Overview

:startdoc::middleware profile the workflow execution time

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(stack, config = {}) ⇒ Profiler

Returns a new instance of Profiler.



15
16
17
18
19
# File 'lib/tap/middlewares/profiler.rb', line 15

def initialize(stack, config={})
  super
  reset
  at_exit { app.quiet = false; app.log(:profile, "\n" + summary.join("\n")) }
end

Instance Attribute Details

#app_timeObject (readonly)

Returns the value of attribute app_time.



11
12
13
# File 'lib/tap/middlewares/profiler.rb', line 11

def app_time
  @app_time
end

#countsObject (readonly)

Returns the value of attribute counts.



13
14
15
# File 'lib/tap/middlewares/profiler.rb', line 13

def counts
  @counts
end

#nodesObject (readonly)

Returns the value of attribute nodes.



12
13
14
# File 'lib/tap/middlewares/profiler.rb', line 12

def nodes
  @nodes
end

Instance Method Details

#call(node, inputs = []) ⇒ Object



36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/tap/middlewares/profiler.rb', line 36

def call(node, inputs=[])
  @app_time += Time.now - @last if @last
  
  start = Time.now
  result = super
  elapsed = Time.now - start
  
  nodes[node] += elapsed
  counts[node] += 1
  
  @last = Time.now
  result
end

#resetObject



21
22
23
24
25
26
# File 'lib/tap/middlewares/profiler.rb', line 21

def reset
  @app_time = 0
  @last = nil
  @nodes = Hash.new(0)
  @counts = Hash.new(0)
end

#summaryObject



50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
# File 'lib/tap/middlewares/profiler.rb', line 50

def summary
  lines = []
  lines << "App Time: #{app_time}s"
  lines << "Node Time: #{total_time}s"
  lines << "Nodes Run: #{total_counts}"
  lines << "Breakdown:"
  
  nodes_by_class = {}
  nodes.each_key do |node|
    (nodes_by_class[node.class.to_s] ||= []) << node
  end
  
  nodes_by_class.keys.sort.each do |node_class|
    nodes_by_class[node_class].each do |node|
      lines << "- #{node_class}: [#{nodes[node]}, #{counts[node]}]"
    end
  end
  
  lines
end

#total_countsObject



32
33
34
# File 'lib/tap/middlewares/profiler.rb', line 32

def total_counts
  counts.values.inject(0) {|sum, n| sum + n }
end

#total_timeObject



28
29
30
# File 'lib/tap/middlewares/profiler.rb', line 28

def total_time
  nodes.values.inject(0) {|sum, elapsed| sum + elapsed }
end