ActiveRecord SQL Runtime

How can I get the SQL query execution time in rails? I see time in logs, for example:

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

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

+7
ruby-on-rails activerecord
source share
2 answers

You can use ActiveSupport :: Notifications to get SQL statement execution time.

You must have the sql.active_record tool to find out 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 has not been tested, so I can not guarantee its performance, but it must

+16
source share

try it

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

All Articles