Tutorial :Benchmarking rails ActiveRecord Queries


I'm looking to benchmark a couple of my ActiveRecord requests in my app. What's the simplest way in the console to benchmark something like



User.find(:first, :select => :id, :conditions => ["name = ?","Joe"]).id  



Use script/performance/benchmarker:

script/performance/benchmarker 2000 "User.find_by_name('Joe').id" "User.first(:conditions => {:name => 'Joe'}, :select => 'id').id"  

On my dev machine, this reports:

            user     system      total        real  #1      1.110000   0.070000   1.180000 (  1.500366)  #2      0.800000   0.050000   0.850000 (  1.078444)  

Thus, the 2nd method appears to be faster, since it has less work to do. Of course, you should benchmark this on your production machine, using the production environment:

RAILS_ENV=production script/performance/benchmarker 2000 "User.find_by_name('Joe').id" "User.first(:conditions => {:name => 'Joe'}, :select => 'id').id"  

It might change conditions a bit for you.


This question is a bit old and needs an updated answer. The easiest way to benchmark the query outside of a production scenario would be to run it in rails console (the benchmarker script isn't in Rails anymore.) Then you can simply test using the Benchmark class built into Ruby. Run the following in Rails:

puts Benchmark.measure { User.find_by_name("Joe").id }  puts Benchmark.measure { User.find(:first, :select => :id, :conditions => ["name = ?","Joe"]).id }  

I'd run the above 5 times, discard the min and max, and take the average cost of the remaining three runs to figure out which query is going to give you better performance.

This is the most accurate solution to get the true cost of a query since Rails doesn't show you the cost to actually construct your objects. So while @Slobodan Kovacevic answer is correct in that the log shows you how log the query takes, the long doesn't give you object construction time which may be less for your second query since you're only populating a single field vs all the user fields.


In development mode each query is timed and logged in log/development.log. You'll have lines like:

Ad Load (1.4ms)  SELECT "ads".* FROM "ads" ORDER BY created_at DESC  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »