Debian Codegraph @

tools/groonga-memory-usage-analyzer.rb

raw symbols SCIP
1 #!/usr/bin/env ruby
2
3 class Memory < Struct.new(:size, :file, :line, :function)
4 def location
5 "#{file}:#{line}"
6 end
7 end
8
9 class LocationGroup
10 attr_reader :location
11 attr_reader :memories
12 def initialize(location)
13 @location = location
14 @memories = []
15 end
16
17 def add(memory)
18 @memories << memory
19 end
20
21 def total_size
22 @memories.inject(0) do |sum, memory|
23 sum + memory.size
24 end
25 end
26
27 def average_size
28 total_size / @memories.size.to_f
29 end
30
31 def max_size
32 @memories.collect(&:size).max
33 end
34
35 def min_size
36 @memories.collect(&:size).min
37 end
38 end
39
40 class Statistics
41 def initialize
42 @location_groups = {}
43 end
44
45 def add(memory)
46 group = location_group(memory.location)
47 group.add(memory)
48 end
49
50 def sort_by_size
51 @location_groups.values.sort_by do |group|
52 group.total_size
53 end
54 end
55
56 private
57 def location_group(location)
58 @location_groups[location] ||= LocationGroup.new(location)
59 end
60 end
61
62 statistics = Statistics.new
63
64 ARGF.each_line do |line|
65 case line
66 when /\Aaddress\[\d+\]\[not-freed\]:\s
67 (?:0x)?[\da-fA-F]+\((\d+)\):\s
68 (.+?):(\d+):\s(\S+)/x
69 size = $1.to_i
70 file = $2
71 line = $3.to_i
72 function = $4.strip
73 memory = Memory.new(size, file, line, function)
74 statistics.add(memory)
75 end
76 end
77
78 def format_size(size)
79 if size < 1024
80 "#{size}B"
81 elsif size < (1024 * 1024)
82 "%.3fKiB" % (size / 1024.0)
83 elsif size < (1024 * 1024 * 1024)
84 "%.3fMiB" % (size / 1024.0 / 1024.0)
85 elsif size < (1024 * 1024 * 1024 * 1024)
86 "%.3fGiB" % (size / 1024.0 / 1024.0 / 1024.0)
87 else
88 "#{size}B"
89 end
90 end
91
92 puts("%10s(%10s:%10s:%10s): %s(%s)" % [
93 "Total",
94 "Average",
95 "Max",
96 "Min",
97 "Location",
98 "N allocations",
99 ])
100 top_allocated_groups = statistics.sort_by_size.reverse_each.take(10)
101 top_allocated_groups.each do |group|
102 puts("%10s(%10s:%10s:%10s): %s(%d)" % [
103 format_size(group.total_size),
104 format_size(group.average_size),
105 format_size(group.max_size),
106 format_size(group.min_size),
107 group.location,
108 group.memories.size,
109 ])
110 end
111
112 puts
113 puts("Top allocated location's details")
114 top_allocated_group = top_allocated_groups.first
115 target_memories = top_allocated_group.memories
116 size_width = Math.log10(target_memories.size).floor + 1
117 target_memories.group_by(&:size).sort_by do |size, memories|
118 size * memories.size
119 end.reverse_each do |size, memories|
120 total_size = memories.inject(0) {|sum, memory| sum + memory.size}
121 puts("%10s(%10s * %#{size_width}d): %s" % [
122 format_size(total_size),
123 format_size(size),
124 memories.size,
125 memories.first.location,
126 ])
127 end