Skip to content

Instantly share code, notes, and snippets.

@tiegz
Last active Aug 29, 2015
Embed
What would you like to do?
Object Profiler for ruby 2.1.0+
module ObjectSpace
def self.profile(&blk)
require 'objspace'
enable_gc = GC.disable
ObjectSpace.trace_object_allocations(&blk)
objs = Hash.new(0)
ObjectSpace.each_object { |o|
if (file = ObjectSpace.allocation_sourcefile(o)) && (line = ObjectSpace.allocation_sourceline(o))
objs["#{file}:#{line}:#{o.class.name}"] += 1
end
}
ObjectSpace.trace_object_allocations_clear
GC.enable if enable_gc
objs
end
end
# require 'pp'
# objs = ObjectSpace.profile do
# a_new_array = ["a new string"]
# end
#
# pp objs
#
# => {"object_profiler.rb:21:Array"=>1, "object_profiler.rb:21:String"=>1}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment