ruby-on-rails - 如何记录启动 Rails 应用程序所需的时间

标签 ruby-on-rails ruby ruby-on-rails-6 puma

如何记录 Rails 应用程序在准备好处理请求之前所花费的启动持续时间?

通过在 boot.rb` 中添加 puts "Rails app booted in #{(boot_start - Time.now)} 秒" 的简单方法无法按预期工作。

# config/boot.rb
boot_start = Time.now

require "bundler/setup"
require "bootsnap/setup" if ENV["RAILS_ENV"] == "development"

puts "Rails app booted in #{(boot_start - Time.now)} seconds"

我需要的是

请注意,我上面提到的简单方法会打印 Web 服务器实际启动之前的持续时间:

app_1       | Database 'XXX_staging' already exists
app_1       | Rails app booted in -1.2772e-05 seconds # Not only it appears before the server is ready
app_1       | Rails app booted in -1.01e-05 seconds   # But is also duplicated for some reason
app_1       | => Booting Puma
app_1       | => Rails 6.1.3.2 application starting in staging
app_1       | => Run `bin/rails server --help` for more startup options
app_1       | [12] Puma starting in cluster mode...
app_1       | [12] * Puma version: 5.3.1 (ruby 3.0.1-p64) ("Sweetnighter")
app_1       | [12] *  Min threads: 5
app_1       | [12] *  Max threads: 5
app_1       | [12] *  Environment: staging
app_1       | [12] *   Master PID: 12
app_1       | [12] *      Workers: 2
app_1       | [12] *     Restarts: (✔) hot (✖) phased
app_1       | [12] * Preloading application
app_1       | [12] * Listening on http://0.0.0.0:3000

我知道 Web 服务器是异步启动的,测量方式将与用于运行应用程序的实际 Web 服务器(本例中为 puma)耦合,但如何使用任何 Web 服务器实现这一点的示例可能会很有用.

最佳答案

您可以将以下代码添加到您的 profile/boot.rb 中,然后运行 ​​time bundle exec rakeenvironment |排序:

# config/boot.rb

require 'benchmark'

def require(file_name)
  result = nil

  time = Benchmark.realtime do
    result = super
  end

  if time > 0.1
    puts "#{time} #{file_name}"
  end

  result
end

它应该为您提供类似于此的输出:

0.16465099999913946 ruby_parser
0.1686829999962356 sprockets/railtie
0.1764029999903869 rails
0.2461370000091847 pg_ext
0.24949699998251162 pg
0.26813800001400523 active_record/connection_adapters/postgresql_adapter
0.32413899997482076 mimemagic
0.3775960000057239 active_record/connection_adapters/postgis_adapter
0.4651059999887366 rails/all
0.549659000011161 rubocop
7.2341489999962505 /Users/leo/code/Flatlooker/config/environment.rb
bundle exec rake environment  7,05s user 2,82s system 67% cpu 14,615 total
sort  0,00s user 0,00s system 0% cpu 14,615 total

另一个不错的选择是 gem Bumbler

Credit to https://mildlyinternet.com/code/profiling-rails-boot-time.html

关于ruby-on-rails - 如何记录启动 Rails 应用程序所需的时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68366041/

相关文章:

ruby-on-rails - rails api 和 node.js 应用程序之间的用户身份验证

ruby-on-rails - Rails 3 的良好身份验证

ruby-on-rails - 如何在事件模型序列化程序中使用设计 current_user

ruby - 如何在 Ruby 中动态创建二维数组?

php - RUBY 和 RAILS 相对于 PHP 和 CODEIGNITER 的主要优势是什么

ruby-on-rails - 有没有办法测试 PostCSS Autoprefixer 是否正常工作?专用于 Rails 6

ruby-on-rails - 使用 capistrano 部署时在服务器上运行迁移

ruby - 如何使用 Ruby 的 SOAP::Attachment 类?

ruby-on-rails - Webpacker 部署问题 Rails 6

ruby-on-rails - 如何在 Rails 6 中配置 Jasmine?