Class: ObjectSpaceProfile

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

Overview

ObjectSpaceProfile provides a tool for assessing how many Ruby objects are in memory. By taking measures over time you can watch the change in the number of objects, and identify situations in which we’re holding on to more objects than intended. Sometimes it may be necessary to generate a report with each cycle, especially if performance means you aren’t getting to the end of the process.

Examples:

def method_we_are_profiling
  osp = ObjectSpaceProfile.new
  Record.each_batch do |batch|
    ops.measure
    do_stuff
  end
  osp.report('my_data.csv')
end

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeObjectSpaceProfile

Returns a new instance of ObjectSpaceProfile.



20
21
22
# File 'lib/object_space_profile.rb', line 20

def initialize
  @data = []
end

Instance Attribute Details

#dataObject (readonly)

Returns the value of attribute data.



18
19
20
# File 'lib/object_space_profile.rb', line 18

def data
  @data
end

Instance Method Details

#measure(garbage_collect = true) ⇒ Object

Take an object space reading

Parameters:

  • garbage_collect (Boolean) (defaults to: true)

    Whether to perform garbage collection before taking a reading. slower, but will avoid the typical sawtooth profile.



29
30
31
32
33
34
35
36
37
38
39
# File 'lib/object_space_profile.rb', line 29

def measure(garbage_collect = true)
  ObjectSpace.garbage_collect if garbage_collect
  profile = Hash.new { |store, class_name| store[class_name] = 0 }
  ObjectSpace.each_object do |o|
    # This handles ALL objects, including anything that inherits from
    # BasicObject, or redefines class. (Ie. configatron)
    name = Kernel.instance_method(:class).bind_call(o).name
    profile[name] += 1
  end
  @data << profile
end

#report(filename) ⇒ Object

Export the collected information to the csv file named filename

Parameters:

  • filename (String)

    The csv file to generate (In the application base directory)



43
44
45
46
47
# File 'lib/object_space_profile.rb', line 43

def report(filename)
  CSV.open(filename, 'wb', headers: headers, write_headers: true) do |csv|
    @data.each_with_index { |data, index| csv << data.merge({ 'Iteration' => index }) }
  end
end