Quick and dirty RubyProf wrapper
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
# frozen_string_literal: true | |
# Ref.: https://hiltmon.com/blog/2012/02/27/quick-and-dirty-rails-performance-profiling/ | |
# Usage: | |
# RubyProfiler.prof('my_profile') do | |
# slow code | |
# ... | |
# end | |
# You can also pass a `enabled: false` to disable profiler | |
# | |
# It will generate 'tmp/profiles/my_profile/<timestamp>_call_stack.html' | |
module RubyProfiler | |
DIR = File.join(Rails.root, 'tmp', 'profiles') | |
# @param [String] sub_dir_name name of sub-directory for profiles | |
# @param [Object] enabled flag to enable/disable profiler | |
def self.prof(sub_dir_name, enabled: true) | |
return yield unless enabled | |
# create dir & sub_dir automatically | |
FileUtils.mkdir_p(DIR) unless File.exist?(DIR) | |
subdir = File.join(DIR, sub_dir_name) | |
FileUtils.mkdir_p(subdir) unless File.exist?(subdir) | |
require 'ruby-prof' | |
RubyProf.start | |
begin | |
yield | |
ensure | |
results = RubyProf.stop | |
file_path = File.join(subdir, "#{Time.now.to_i}_call_stack.html") | |
File.open(file_path, 'w') do |file| | |
RubyProf::CallStackPrinter.new(results).print(file) | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment