Skip to content

Instantly share code, notes, and snippets.

@kidlab
Last active November 3, 2017 04:21
Embed
What would you like to do?
Ruby memory conscious

MEASURING MEMORY USAGE

There are several gems that help with determining where a program allocates memory. The two that I most often use are allocation_tracer and memory_profiler.

Both tools can measure a whole program or they can be turned on and off to only measure certain parts of a program. Either method allows you to determine hotspots in your program and then act on the information. For example, while developing kramdown several years ago I found that the HTML converter class allocated huge amounts of throw-away strings. By changing this hotspot to a better alternative kramdown got faster and used less memory.

To get you started on using these two gems, here are two files that are intended to get pre-loaded using the -r switch of the ruby binary (i.e. ruby -I. -ralloc_tracer myscript.rb).

Credit: https://gettalong.org/blog/2017/memory-conscious-programming-in-ruby.html

BEGIN {
require 'allocation_tracer'
ObjectSpace::AllocationTracer.setup(%i{path line type})
ObjectSpace::AllocationTracer.trace
}
END {
require 'pp'
results = ObjectSpace::AllocationTracer.stop
results.reject {|k, v| v[0] < 10}.sort_by{|k, v| [v[0], k[0]]}.each do |k, v|
puts "#{k[0]}:#{k[1]} - #{k[2]} - #{v[0]}"
end
puts "Sum: " + results.inject(0) {|sum, (k,v)| sum + v[0]}.to_s
pp ObjectSpace::AllocationTracer.allocated_count_table
pp :total => ObjectSpace::AllocationTracer.allocated_count_table.values.inject(:+)
}
BEGIN {
require 'memory_profiler'
MemoryProfiler.start
}
END {
report = MemoryProfiler.stop
report.pretty_print
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment