问题
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