Created
July 15, 2015 15:28
Shitty Ruby Rack memory profiler
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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