Class: MemoryProfiler::Reporter

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

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.report(opts = {}, &block) ⇒ Object



5
6
7
8
# File 'lib/memory_profiler/reporter.rb', line 5

def self.report(opts={}, &block)
  report = self.new
  report.run(opts,&block)
end

Instance Method Details

#object_list(generation, rvalue_size, trace) ⇒ Object



50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
# File 'lib/memory_profiler/reporter.rb', line 50

def object_list(generation, rvalue_size, trace)
  results = StatHash.new
  objs = []

  ObjectSpace.each_object do |obj|
    begin
      if !trace || trace.include?(obj.class)
        objs << obj
      end
    rescue
      # may not respond to class so skip
    end
  end

  objs.each do |obj|
    if generation == ObjectSpace.allocation_generation(obj)
      file = ObjectSpace.allocation_sourcefile(obj)
      unless file == __FILE__
        line = ObjectSpace.allocation_sourceline(obj)
        class_path = ObjectSpace.allocation_class_path(obj)
        method_id = ObjectSpace.allocation_method_id(obj)

        class_name = obj.class.name rescue "BasicObject"
        begin
          object_id = obj.__id__

          memsize = ObjectSpace.memsize_of(obj) + rvalue_size
          # compensate for API bug
          memsize = rvalue_size if memsize > 100_000_000_000
          results[object_id] = Stat.new(class_name, file, line, class_path, method_id, memsize)
        rescue
          # __id__ is not defined, give up
        end
      end
    end
  end

  results
end

#run(opts = {}, &block) ⇒ Object



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/memory_profiler/reporter.rb', line 10

def run(opts={},&block)
  allocated, rvalue_size = nil

  top = opts[:top] || 50
  trace = opts[:trace]

  rvalue_size = GC::INTERNAL_CONSTANTS[:RVALUE_SIZE]
  Helpers.full_gc
  GC.disable

  ObjectSpace.trace_object_allocations do
    generation = GC.count
    block.call
    allocated = object_list(generation, rvalue_size, trace)
  end

  results = Results.new
  results.strings_allocated = results.string_report(allocated,top)

  GC.enable

  Helpers.full_gc

  retained = StatHash.new
  ObjectSpace.each_object do |obj|
    begin
      found = allocated[obj.__id__]
      retained[obj.__id__] = found if found
    rescue
      # __id__ is not defined on BasicObject, skip it
      # we can probably trasplant the object_id at this point, 
      # but it is quite rare
    end
  end

  results.register_results(allocated,retained,top)
  results

end