如何在 Rails 中获取 SQL 查询执行时间?我可以在日志中看到时间,例如:
Posting Load (10.8ms) SELECT "postings".* FROM "postings" ORDER BY "postings"."id" ASC LIMIT 1
但是如何以编程方式获得该值(10.08)以在我的代码中进一步使用它?
如何在 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) }