Skip to content

Instantly share code, notes, and snippets.

@palkan
Created January 24, 2022 13:29
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save palkan/a40e028865dc7bc4ccfb6db2ade9c94f to your computer and use it in GitHub Desktop.
Save palkan/a40e028865dc7bc4ccfb6db2ade9c94f to your computer and use it in GitHub Desktop.
Rails boot time profiling

Add the following to application.rb:

$icallbacks = []
$icallbacks.define_singleton_method(:print) do
  puts sort_by { |(a, b)| -b }.map { |(a, b)| "#{b}\t\t#{a}" }.join("\n")
end

ActiveSupport::Notifications.subscribe("load_config_initializer.railties") do |event|
  $icallbacks << [event.payload[:initializer], event.duration]
end

$pcallbacks = []
$pcallbacks.define_singleton_method(:print) do
  puts sort_by { |(a, b)| -b }.map { |(a, b)| "#{b}\t\t#{a.first}:#{a.last}" }.join("\n")
end

require 'active_support/reloader'
require 'benchmark'

ActiveSupport::Reloader.singleton_class.prepend(Module.new do
  def to_prepare(*args, &block)
    wrapper = proc do |*bargs|
      result = nil
      time = Benchmark.realtime do
        result = block.call(*bargs)
      end

      $pcallbacks << [block.source_location, time]

      result
    end

    super(*args, &wrapper)
  end
end)

Then, run rails r 'puts $icallbacks.print', etc.

See also Bumbler.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment