Skip to content

Instantly share code, notes, and snippets.

@tiegz
Last active August 29, 2015 14:03
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tiegz/50bc52abbe6b0082f5c6 to your computer and use it in GitHub Desktop.
Save tiegz/50bc52abbe6b0082f5c6 to your computer and use it in GitHub Desktop.
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