Last active
July 14, 2025 15:06
-
-
Save moofkit/c1ae9739d0a28bcfaea23ab70f94916b to your computer and use it in GitHub Desktop.
Rails track boot time
This file contains hidden or 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
# config/application.rb | |
module MyApp | |
class Application < Rails::Application | |
# .... | |
# NOTE: This is a workaround to measure boot time after all initializers are loaded | |
# `Rails.application.config.after_initialize` included | |
# https://guides.rubyonrails.org/configuring.html#initializers | |
initializer :boot_time, after: :finisher_hook do | |
boot_time = BootTime.instance.boot_time_elapsed_milliseconds | |
Rails.logger.info("Boot time: #{boot_time}ms") | |
end | |
end | |
end |
This file contains hidden or 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
# config/boot.rb | |
# frozen_string_literal: true | |
# Measure boot time | |
require_relative "../lib/boot_time" | |
BootTime.instance.store_start_timestamp | |
ENV["BUNDLE_GEMFILE"] ||= File.expand_path("../Gemfile", __dir__) | |
require "bundler/setup" # Set up gems listed in the Gemfile. | |
require "bootsnap/setup" # Speed up boot time by caching expensive operations. |
This file contains hidden or 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
# lib/boot_time.rb | |
# frozen_string_literal: true | |
require "singleton" | |
class BootTime | |
include Singleton | |
attr_reader :start_timestamp | |
def store_start_timestamp | |
return if @start_timestamp | |
@start_timestamp = Process.clock_gettime(Process::CLOCK_MONOTONIC) | |
end | |
def boot_time_elapsed_milliseconds | |
return 0.0 unless @start_timestamp | |
@boot_time_elapsed_milliseconds ||= (time_since_start * 1000).round(2) | |
end | |
def reset! | |
@start_timestamp = nil | |
@boot_time_elapsed_milliseconds = nil | |
end | |
private | |
def time_since_start | |
Process.clock_gettime(Process::CLOCK_MONOTONIC) - @start_timestamp | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment