Skip to content

Instantly share code, notes, and snippets.

@mateusnava
Last active August 16, 2019 13:42
Show Gist options
  • Select an option

  • Save mateusnava/90c0f43d50cfa6d4ae75c7fbe905d67e to your computer and use it in GitHub Desktop.

Select an option

Save mateusnava/90c0f43d50cfa6d4ae75c7fbe905d67e to your computer and use it in GitHub Desktop.
Memory Leak Analyzer
#########################################################################################################
# Dependencies: rbtrace (https://github.com/tmm1/rbtrace) in the ruby process that will be analyzed #
# Reference: https://samsaffron.com/archive/2015/03/31/debugging-memory-leaks-in-ruby #
#########################################################################################################
require 'json'
class MemoryLeakAnalyzer
attr_reader :filename
def initialize
@filename = "/tmp/leak-analyzer-dump"
end
def data_parsed
# TODO: Read with chunk
File.new(@filename).readlines.map { |line| JSON.parse(line) }
end
def analyze
data_parsed
.group_by{ |row| row["generation"] }
.sort{ |a,b| a[0].to_i <=> b[0].to_i }
.each do |k,v|
puts "generation #{k} objects #{v.count}"
end
nil
end
def analyze_generation(generation)
data_parsed
.filter { |line| line["generation"] == generation }
.group_by{ |row| "#{row["file"]}:#{row["line"]}" }
.sort{ |a,b| b[1].count <=> a[1].count }
.each do |k,v|
puts "#{k} * #{v.count}"
end
nil
end
def dump(pid)
`bundle exec rbtrace -p #{pid} -e 'Thread.new{GC.start; i=File.open("#{filename}", "w"); ObjectSpace.dump_all(output: i); i.close}'`
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment