Skip to content

Instantly share code, notes, and snippets.

@lifo
Created September 17, 2008 23:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lifo/11326 to your computer and use it in GitHub Desktop.
Save lifo/11326 to your computer and use it in GitHub Desktop.
def gc_statistics(description = "", options = {})
#do nothing if we don't have patched Ruby GC
yield and return unless GC.respond_to? :enable_stats
GC.enable_stats || GC.clear_stats
GC.disable if options[:disable_gc]
yield
stat_string = description + ": "
stat_string += "allocated: #{GC.allocated_size/1024}K total in #{GC.num_allocations} allocations, "
stat_string += "GC calls: #{GC.collections}, "
stat_string += "GC time: #{GC.time / 1000} msec"
GC.log stat_string
GC.dump if options[:show_gc_dump]
GC.enable if options[:disable_gc]
GC.disable_stats
end
class Hello
def initialize
@target = (1..100).to_a
end
def method_missing(method, *args)
if block_given?
@target.send(method, *args) { |*block_args| yield(*block_args) }
else
@target.send(method, *args)
end
end
end
class World
def initialize
@target = (1..100).to_a
end
def method_missing(method, *args, &block)
if block_given?
@target.send(method, *args, &block)
else
@target.send(method, *args)
end
end
end
h = Hello.new
w = World.new
gc_statistics("Without Block map") { 10000.times { h.map {|x| x} } }
gc_statistics(" With Block map") { 10000.times { w.map {|x| x} } }
gc_statistics("Without Block min") { 10000.times { h.min } }
gc_statistics(" With Block min") { 10000.times { w.min } }
Without Block map: allocated: 11992K total in 2040004 allocations, GC calls: 645, GC time: 394 msec
With Block map: allocated: 6992K total in 90004 allocations, GC calls: 10, GC time: 17 msec
Without Block min: allocated: 78K total in 20004 allocations, GC calls: 5, GC time: 4 msec
With Block min: allocated: 78K total in 20004 allocations, GC calls: 4, GC time: 3 msec
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment