Class: SamplingProf

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

Constant Summary collapse

DEFAULT_OUTPUT_FILE =
'profile.txt'

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(sampling_interval = 0.1, &output_handler) ⇒ SamplingProf

options:

sampling_interval: default to 0.1 second
&output_handler: default to write into output_file


16
17
18
19
# File 'lib/sampling_prof.rb', line 16

def initialize(sampling_interval=0.1, &output_handler)
  @profiler = SamplingProfiler.new(sampling_interval)
  @output_handler = block_given? ? output_handler : default_output_handler
end

Instance Attribute Details

#output_fileObject



41
42
43
# File 'lib/sampling_prof.rb', line 41

def output_file
  @output_file ||= DEFAULT_OUTPUT_FILE
end

Instance Method Details

#default_output_handlerObject



52
53
54
55
56
57
58
# File 'lib/sampling_prof.rb', line 52

def default_output_handler
  lambda do |data|
    File.open(output_file, 'w') do |f|
      f.write(data)
    end
  end
end

#flat_report(nodes, counts) ⇒ Object



81
82
83
84
85
86
87
88
89
# File 'lib/sampling_prof.rb', line 81

def flat_report(nodes, counts)
  total = counts.map{|_,sc,tc| sc}.reduce(:+)
  reports = counts.reject{|_,sc,tc| sc == 0}.sort_by{|_,sc,tc| -sc}.map do |id, sc, tc|
    [sc, '%.2f%' % (100 * sc.to_f/total),
     tc, '%.2f%' % (100 * tc.to_f/total),
     nodes[id]]
  end
  [total, reports]
end

#profile(handler = nil, &block) ⇒ Object



45
46
47
48
49
50
# File 'lib/sampling_prof.rb', line 45

def profile(handler=nil, &block)
  start(handler)
  yield
ensure
  stop
end

#profiling?Boolean

Returns:

  • (Boolean)


29
30
31
# File 'lib/sampling_prof.rb', line 29

def profiling?
  @profiler.profiling?
end

#report(type, output = $stdout) ⇒ Object



60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
# File 'lib/sampling_prof.rb', line 60

def report(type, output=$stdout)
  runtime, nodes, counts, call_graph = File.read(output_file).split("\n\n")
  nodes = nodes.split("\n").inject({}) do |ret, l|
    n, i = l.split(',')
    ret[i.to_i] = n
    ret
  end

  counts = counts.split("\n").map do |l|
    l.split(',').map(&:to_i)
  end
  total_samples, report = flat_report(nodes, counts)

  output.puts "runtime: #{runtime.to_f/1000} secs"
  output.puts "total samples: #{total_samples}"
  output.puts "self\t%\ttotal\t%\tname"
  report.first(20).each do |v|
    output.puts v.join("\t")
  end
end

#sampling_intervalObject



33
34
35
# File 'lib/sampling_prof.rb', line 33

def sampling_interval
  @profiler.sampling_interval
end

#start(handler = nil) ⇒ Object



21
22
23
# File 'lib/sampling_prof.rb', line 21

def start(handler=nil)
  @profiler.start(handler || @output_handler)
end

#stopObject



25
26
27
# File 'lib/sampling_prof.rb', line 25

def stop
  @profiler.stop
end

#terminateObject



37
38
39
# File 'lib/sampling_prof.rb', line 37

def terminate
  @profiler.terminate
end