Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save MichaelXavier/483711 to your computer and use it in GitHub Desktop.
Save MichaelXavier/483711 to your computer and use it in GitHub Desktop.
def profile(label=nil, unit = :M)
# trying to see where our memory is going
population = Hash.new{|h,k| h[k] = [0,0]}
array_sizes = Hash.new{|h,k| h[k] = 0}
ObjectSpace.each_object do |object|
# rough estimates, see http://eigenclass.org/hiki.rb?ruby+space+overhead
size = case object
when Array
array_sizes[object.size / 10] += 1
case object.size
when 0..16
20 + 64
else
20 + 4 * object.size * 1.5
end
when Hash; 40 + 4 * [object.size / 5, 11].max + 16 * object.size
when String; 30 + object.size
else 120 # the iv_tbl, etc
end
count, tsize = population[object.class]
population[object.class] = [count + 1, tsize + size]
end
multiplier = unit == :M ? 1048576 : 1
puts "Total Usage #{label}: #{population.values.inject(0.0) {|s,(c,b)| s + b.to_f}/multiplier}#{unit}"
population.sort_by{|k,(c,s)| s}.reverse[0..10].each do |klass, (count, bytes)|
puts "%-20s %7d %9f" % [klass, count, bytes/multiplier]
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment