Skip to content

Instantly share code, notes, and snippets.

@zacstewart
Created July 15, 2015 15:28
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 zacstewart/94711b524b89ab2dc557 to your computer and use it in GitHub Desktop.
Save zacstewart/94711b524b89ab2dc557 to your computer and use it in GitHub Desktop.
Shitty Ruby Rack memory profiler
require 'objspace'
require 'set'
class ObjectAllocationTracer
include ObjectSpace
def initialize(app)
@app = app
@sources = Set.new
@traces = []
end
def call(env)
output = nil
trace_objects do
output = @app.call(env)
end
dump_trace
output
end
private
def dump_trace
CSV.open('object_trace.csv', 'wb', write_headers: true, headers: @sources.to_a << :id) do |csv|
@traces.each_with_index do |trace, i|
csv << trace.merge(id: i)
end
end
end
def trace_objects
trace_object_allocations do
yield
end
trace = each_object(String).each_with_object(Hash.new(0)) do |obj, t|
file = allocation_sourcefile(obj)
line = allocation_sourceline(obj)
next if file.nil? || line.nil?
source = "#{file}:#{line}".to_sym
@sources << source
t[source] += 1
end
@traces << trace
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment