Last active
March 5, 2018 11:34
-
-
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)
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 '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