ActiveRecord SQL execution time

最后都变了- 提交于 2019-12-18 04:09:17

问题


How can I get the SQL query execution time in rails? I can see the time in logs, e.g.:

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

But how can I get that value (10.08) programmatically to use it further in my code?


回答1:


You can use ActiveSupport::Notifications to retrieve the runtime of the SQL statements

You should be able to instrument sql.active_record to see how long the SQL call takes

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

This code was not tested, so I can't guarantee it works, but it should




回答2:


try this out

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


来源:https://stackoverflow.com/questions/18240624/activerecord-sql-execution-time

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!