ActiveRecord SQL执行时间

Eug*_*pan 9 activerecord ruby-on-rails

如何在rails中获取SQL查询执行时间?我可以在日志中看到时间,例如:

 Posting Load (10.8ms)  SELECT "postings".* FROM "postings" ORDER BY "postings"."id" ASC LIMIT 1
Run Code Online (Sandbox Code Playgroud)

但是,如何以编程方式获取该值(10.08)以在我的代码中进一步使用它?

Dan*_*ain 20

您可以使用ActiveSupport :: Notifications来检索SQL语句的运行时

您应该能够检测sql.active_recordSQL调用需要多长时间

ActiveSupport::Notifications.subscribe('sql.active_record') do |*args|
  event = ActiveSupport::Notifications::Event.new(*args)
  event.duration #how long it took to run the sql command
end
Run Code Online (Sandbox Code Playgroud)

此代码未经过测试,因此我无法保证其有效,但应该如此


Sac*_*ngh 5

试试这个

time_consumed = Benchmark.measure { Post.limit(1) }
Run Code Online (Sandbox Code Playgroud)

  • 我尝试过,但似乎这显示了在块中​​执行 ruby​​ 的时间,包括所有 activerecord 和 arel 的东西...但我需要确切执行 sql 查询的时间。我需要知道我的数据库插入新记录的速度有多快,而不是 ActiveRecord。 (3认同)