Project

General

Profile

Bug #1152 ยป 1152.patch

Sample patch for discussion - jabley (James Abley), 03/16/2009 09:29 AM

View differences:

lib/profiler.rb (working copy)
1 1
module Profiler__
2 2
  # internal values
3
  @@start = @@stack = @@map = nil
3
  @@start = nil # the start time that profiling began
4
  @@stacks = nil # the map of stacks keyed by thread
5
  @@maps = nil # the map of call data keyed by thread, class and id. Call data contains the call count, total time, 
4 6
  PROFILE_PROC = proc{|event, file, line, id, binding, klass|
5 7
    case event
6 8
    when "call", "c-call"
7 9
      now = Process.times[0]
8
      @@stack.push [now, 0.0]
10
      stack = (@@stacks[Thread.current] ||= [])
11
      stack.push [now, 0.0]
9 12
    when "return", "c-return"
10 13
      now = Process.times[0]
11 14
      key = [klass, id]
12
      if tick = @@stack.pop
13
        data = (@@map[key] ||= [0, 0.0, 0.0, key])
15
      stack = (@@stacks[Thread.current] ||= [])
16
      if tick = stack.pop
17
        threadMap = (@@maps[Thread.current] ||= {})
18
        data = (threadMap[key] ||= [0, 0.0, 0.0, key])
14 19
        data[0] += 1
15 20
        cost = now - tick[0]
16 21
        data[1] += cost
17 22
        data[2] += cost - tick[1]
18
        @@stack[-1][1] += cost if @@stack[-1]
23
        stack[-1][1] += cost if stack[-1]
19 24
      end
20 25
    end
21 26
  }
22 27
module_function
23 28
  def start_profile
24 29
    @@start = Process.times[0]
25
    @@stack = []
26
    @@map = {}
30
    @@stacks = {}
31
    @@maps = {}
27 32
    set_trace_func PROFILE_PROC
28 33
  end
29 34
  def stop_profile
......
33 38
    stop_profile
34 39
    total = Process.times[0] - @@start
35 40
    if total == 0 then total = 0.01 end
36
    data = @@map.values
41
    totals = {}
42
    @@maps.values.each { |threadMap|
43
      threadMap.each {|key, data|
44
        total_data = (totals[key] ||= [0, 0.0, 0.0, key])
45
        total_data[0] += data[0]
46
        total_data[1] += data[1] #TODO summing this field doesn't make much sense?
47
        total_data[2] += data[2] 
48
      }
49
    }
50

  
51
    # Maybe we should show a per thread output and a totals view?
52

  
53
    data = totals.values
37 54
    data = data.sort_by{|x| -x[2]}
38 55
    sum = 0
39 56
    f.printf "  %%   cumulative   self              self     total\n"