Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails: 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_by_name("Joe").id

versus

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

Thanks

like image 707
Splashlin Avatar asked Aug 05 '10 21:08

Splashlin


2 Answers

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.

like image 78
Gavin Miller Avatar answered Sep 28 '22 07:09

Gavin Miller


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
like image 21
Slobodan Kovacevic Avatar answered Sep 28 '22 08:09

Slobodan Kovacevic