#!/usr/bin/ruby
# 2013-01-14 10:51
# perf-sum-selftime-g.rb  DWF
# Usage:  perf-sum-selftime-g.rb [file ...]
# Input:  one or more perf scripts, or a concatenation of perf scripts,
#         in the default CALLCHAINS FORMAT
# Output:  self time by function.
# Tested only on simple cases of profiling a single application, with no
# curveballs like spaces in function names.
state = 0
samples = 0
counts = Hash.new(0)
ARGF.lines do |line|
  if line[0] != "#"
    case state
    when 0  # Header line of a sample
      raise "Input format error 0" if line[0] == "\t"
      state = 1
    when 1  # Currently executing function
      raise "Input format error 1" if line[0] != "\t"
      counts[line.split(' ',2)[1]] += 1
      samples += 1
      state = 2
    when 2  # Rest of call chain
      if line[0] == "\n"
        state = 0
      elsif line[0] != "\t"
        raise "Input format error 2"
      end
    end
  end
end
decimals = Math.log10(samples).ceil + 1
outbuf = []
counts.each do |fn, count|
  # Ruby has rationals, but right now we just want the float.
  proportion = Float(count) / samples
  outbuf.push ("%.#{decimals}f %s" % [proportion, fn])
end
puts "#{samples} samples"
puts outbuf.sort!.reverse!
