DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Basic Memory Profiling

05.29.2008
| 1826 views |
  • submit to reddit
        Simple memory usage by class dump using ObjectSpace.

s = Hash.new(0);
ObjectSpace.each_object do |o|
  s[o.class] += Marshal.dump(o).size rescue 0
end

w = s.keys.map{|v|v.to_s.length}.max
puts s.to_a.sort{|a,b|b[1]<=>a[1]}.map{|k,v|"%#{w}s %d"%[k,v]}.join("\n")
puts "#{' ' * w} #{s.to_a.inject(0){|n,a| n += a[1]}}"