Skip to content

Instantly share code, notes, and snippets.

@electron0zero
Created February 5, 2020 19:34
Show Gist options
  • Save electron0zero/261382b12a53673ad920bcd009044497 to your computer and use it in GitHub Desktop.
Save electron0zero/261382b12a53673ad920bcd009044497 to your computer and use it in GitHub Desktop.
Quick and dirty RubyProf wrapper
# 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