Class: LeakProfiler::Allocations

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(logger:, interval:, max_allocations:, max_referrers:, max_sample_objects:) ⇒ Allocations

Returns a new instance of Allocations.



19
20
21
22
23
24
25
# File 'lib/leak_profiler/allocations.rb', line 19

def initialize(logger:, interval:, max_allocations:, max_referrers:, max_sample_objects:)
  @logger = logger
  @interval = interval
  @max_allocations = max_allocations
  @max_referrers = max_referrers
  @max_sample_objects = max_sample_objects
end

Instance Attribute Details

#threadObject (readonly)

Returns the value of attribute thread.



13
14
15
# File 'lib/leak_profiler/allocations.rb', line 13

def thread
  @thread
end

Instance Method Details

#reportObject



27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
# File 'lib/leak_profiler/allocations.rb', line 27

def report
  @thread = Thread.start do
    loop do
      ObjectSpace.trace_object_allocations_start
      sleep(@interval)
      ObjectSpace.trace_object_allocations_stop

      allocations = Hash.new { |h, k| h[k] = {} }
      allocations_by_class = Hash.new { |h, k| h[k] = 0 }

      ObjectSpace.each_object.each do |obj|
        begin
          klass = obj_class(obj)
          allocations_by_class[klass] += ObjectSpace.memsize_of(obj)
        rescue StandardError
        end

        key = allocated_location(obj)
        allocations[key][:metrics] ||= Hash.new { |h, k| h[k] = 0 }
        allocations[key][:metrics][:count] += 1
        allocations[key][:metrics][:bytes] += ObjectSpace.memsize_of(obj)

        allocations[key][:sample_objects] ||= []
        allocations[key][:sample_objects] << obj
      end

      allocations.each_value do |v|
        v[:sample_objects] = v[:sample_objects].sample(@max_sample_objects)
      end

      report_allocations_class(allocations_by_class)
      report_allocations(allocations)
      report_referrer_objects(allocations)

      allocations.each_value(&:clear)
      allocations.clear
      allocations_by_class.clear
    rescue StandardError => e
      @logger.add(Logger::Severity::ERROR, "Error occurred: #{e.message}, backtrace: #{e.backtrace.join("\n")}")
    end
  end
end