ActiveRecord SQL执行时间

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

Posting Load (10.8ms) SELECT "postings".* FROM "postings" ORDER BY "postings"."id" ASC LIMIT 1 

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

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

您应该能够检测sql.active_record以查看SQL调用需要多长时间

 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 

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

试试这个

 time_consumed = Benchmark.measure { Post.limit(1) }