Skip to content

Instantly share code, notes, and snippets.

@eric
Created December 28, 2009 02:18
Show Gist options
  • Save eric/264496 to your computer and use it in GitHub Desktop.
Save eric/264496 to your computer and use it in GitHub Desktop.
A simple tool to gather memory usage when files are required. More info at: http://bitmonkey.net/post/308322913
#
# Created by Eric Lindvall <[email protected]>
#
# WHAT: Provides a simple overview of memory allocation occuring during a
# require.
#
# For a longer explanation, see my post at:
#
# http://bitmonkey.net/post/308322913/tracking-initial-memory-usage-by-file-in-ruby
#
# NOTE: The numbers provided are of self + children, meaning the same will
# be attributed to multiple files at once.
#
# Also, memory that is no longer referenced (and would be freed) is still
# taken into account.
#
# 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 }
$require_stats_top ||= 20
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).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
> ruby -rrequire_tracking -e "require 'active_support'"
Memory used by file:
File KB
------------- --------
rubygems: 5,421
active_support: 4,296
active_support/core_ext: 2,361
active_support/json: 1,161
active_support/json/encoding: 1,063
rubygems/config_file: 921
yaml: 877
yaml/rubytypes: 669
date: 573
active_support/vendor: 524
rubygems/source_index: 490
rubygems/command_manager: 448
commands/abstract_command: 446
rubygems/local_remote_options: 428
builder: 407
uri: 406
rubygems/command: 399
builder/xmlmarkup: 393
json: 383
builder/xmlbase: 346
@deepak
Copy link

deepak commented Jul 6, 2010

thanks, added time from gist#140012, http://gist.github.com/465431

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment