简体   繁体   English

基准测试轨道ActiveRecord查询

[英]Benchmarking rails ActiveRecord Queries

I'm looking to benchmark a couple of my ActiveRecord requests in my app. 我想在我的应用程序中对我的几个ActiveRecord请求进行基准测试。 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 谢谢

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. 在生产场景之外对查询进行基准测试的最简单方法是在rails console运行它(基准测试脚本不再在Rails中。)然后,您可以使用Ruby内置的Benchmark类进行Benchmark Run the following in Rails: 在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. 我将运行以上5次,丢弃最小值和最大值,并取其余三次运行的平均成本来确定哪个查询将为您提供更好的性能。

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 . 这是获得查询真实成本的最准确解决方案,因为Rails不会向您显示实际构建对象的成本 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. 因此,虽然@Slobodan Kovacevic的答案是正确的,因为日志显示了查询所记录的日志,但是长时间没有给出对象构造时间,这对于第二个查询可能更少,因为您只填充单个字段而不是所有用户字段。

In development mode each query is timed and logged in log/development.log. 在开发模式下,每个查询都会定时并记录在log / development.log中。 You'll have lines like: 你会有这样的行:

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

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. 它可能会改变你的条件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM