# # Created by Eric Lindvall # # Please note: The numbers provided are of self and children, meaning, you # won't be able to add them all up to get the total memory usage of the app. # # It also does not take into account memory that was allocated and then freed. # # It is intended to give a simple overview of allocations to track down gross # offenders, not give an exact view of your memory usage. # if GC.respond_to?(:enable_stats) module RequireTracking def require(*args) start_allocated_size = GC.allocated_size super ensure $require_stats[args.first] += (GC.allocated_size - start_allocated_size) end def numeric_thousands_indicators(number) number.to_s.gsub(/(\d)(?=\d{3}+(?:\.|$))(\d{3}\..*)?/,'\1,\2') end end Object.send(:include, RequireTracking) Kernel.send(:include, RequireTracking) $require_stats = Hash.new { |h,k| h[k] = 0 } GC.enable_stats GC.clear_stats at_exit do puts "Memory used by file:" puts " %40s %s" % [ 'File', 'KB' ] puts " %40s %s" % [ '-------------', '--------' ] $require_stats.sort_by { |k,v| -v }.slice(0, $require_stats_top || 20).each do |(k,v)| puts "%40s: %s" % [ k, numeric_thousands_indicators(v / 1024) ] end end else puts "Warning: Not running with an interpreter with GC statistics" end