Skip to content

Instantly share code, notes, and snippets.

@katpadi
Last active March 5, 2018 11:34
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 katpadi/79d63e4626359c2e10496492c0460bd9 to your computer and use it in GitHub Desktop.
Save katpadi/79d63e4626359c2e10496492c0460bd9 to your computer and use it in GitHub Desktop.
My Ruby Profiler - wraps code to be profiled and prints result in a nice way (uses ruby-prof)
require 'ruby-prof'
#
# This will use ruby-prof and print in a nice way.
#
# Input params:
# file_name = File name of output
# printer = graph || flat || stack
#
# Output format:
# E.g.:
# tmp/profilers/something-2418870541/graph.html
# flat.html
# stack.html
module DevProfiler
def self.profile(file_name, printer = 'stack', &block)
dir = File.join(Rails.root, 'tmp', 'profilers' )
# Create dir automatically
FileUtils.mkdir_p dir unless File.exist? dir
# Do the profiling
RubyProf.start
block_response = block.call
result = RubyProf.stop
subdir = File.join(dir, "#{file_name}-#{Time.now.to_i}")
FileUtils.mkdir_p subdir unless File.exist? subdir
if printer == 'graph'
File.open(File.join(subdir, 'graph.html'), 'w') do |file|
RubyProf::GraphHtmlPrinter.new(result).print(file)
end
elsif printer == 'flat'
File.open(File.join(subdir, 'flat.txt'), 'w') do |file|
RubyProf::FlatPrinterWithLineNumbers.new(result).print(file)
end
else
File.open(File.join(subdir, 'stack.html'), 'w') do |file|
RubyProf::CallStackPrinter.new(result).print(file)
end
end
# Make sure to return the block response still
block_response
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment