Skip to content

Instantly share code, notes, and snippets.

@Narnach
Created July 16, 2014 09:57
Show Gist options
  • Save Narnach/085ff8713b80f0b226ae to your computer and use it in GitHub Desktop.
Save Narnach/085ff8713b80f0b226ae to your computer and use it in GitHub Desktop.
Simple memory usage counter which diffs vs the last call. Built for rails, but can work anywhere.
# Add this to the very TOP of config/application.rb, before the first statement
require 'pp'
module OSCount
def self.count(msg, force_count: false)
return if ENV['RAILS_ENV'] == 'test'
count = ObjectSpace.count_objects
last_count = Thread.current['OSCount.last_count']
Thread.current['OSCount.last_count'] = count
show_count = last_count.nil?
show_count = true if force_count
free_rate = count[:FREE].to_f / count[:TOTAL]
if show_count
puts "OSCount first: #{msg} (free rate: #{free_rate.round(4)})"
pp count
end
if last_count
diff = {}
count.each do |key, old_value|
diff[key] = last_count.fetch(key, 0) - old_value
end
puts "OSCount diff: #{msg}"
pp diff
end
nil
end
end
OSCount.count('before application.rb')
# Inside of ApplicationController add this:
# class ApplicationController < ActionController::Base
# Put this at the very top
around_filter :debug_object_space
def debug_object_space
OSCount.count('before request')
yield
OSCount.count('after request', force_count: true)
end
# ... the rest of application controller
# end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment