ActiveRecord SQL execution time

activerecord, ruby-on-rails

Solution

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

Problem

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?

Original source