Last active
August 29, 2015 14:01
-
-
Save bry4n/0362baf633d72901c423 to your computer and use it in GitHub Desktop.
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
# Usage: | |
# | |
# tracer = Rails::Tracer.new | |
# tracer.trace("user_find") do | |
# @user = User.find(1) | |
# end | |
# | |
# View report | |
# $ open user_find.html | |
module Rails | |
class Tracer | |
attr_accessor :stats, :traces, :trace | |
def initialize(options = {}) | |
@filter = options[:filter] || /Rails|Active|Action/ | |
@stats = [] | |
@traces = {} | |
@trace = TracePoint.trace(:a_call) do |tp| | |
@traces[tp.defined_class.to_s] ||= {} | |
@traces[tp.defined_class.to_s][tp.method_id] ||= 0 | |
@traces[tp.defined_class.to_s][tp.method_id] += 1 | |
end | |
end | |
def trace(name = "stats") | |
@trace.enable | |
yield | |
@trace.disable | |
generate_report! | |
write_report!(name) | |
end | |
def generate_report! | |
@traces.each do |klass, value| | |
klass = klass.gsub("<",'').gsub(">", '').to_s | |
next unless klass =~ @filter | |
value.each do |name, count| | |
@stats << ["#{klass} - #{name}", count] | |
end | |
end | |
@stats = @stats.sort_by {|x| x.last}.reverse | |
end | |
def write_report!(name) | |
name = name.gsub(/\s+/,'_').underscore | |
File.open("#{name}.html", "w+") do |f| | |
f.puts "<html>" | |
f.puts "<head><title>#{name.titleize}</title></head>" | |
f.puts "<body>" | |
f.puts "<h1>#{name.titleize}</h1>" | |
f.puts "<table>" | |
f.puts "<tr><th>No.</th><th>Name</th><th>Count</th></tr>" | |
@stats.each_with_index do |stat, i| | |
f.puts "<tr>" | |
f.puts "<td>#{i+1}</td><td>#{stat[0]}</td><td>#{stat[1]}</td>" | |
f.puts "</tr>" | |
end | |
f.puts "</body>" | |
f.puts "</html>" | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment