2010-08-05 106 views
9

我期待在我的应用程序中对几个ActiveRecord请求进行基准测试。什么是在控制台基准像Benchmarking rails ActiveRecord查询

User.find_by_name("Joe").id 

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

感谢

回答

1

使用脚本/性能/ benchmarker:

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

在我的dev的机器,这样的报道:

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

因此,第二个方法看起来加快速度,因为它的工作量较少。当然,您应该在生产机器上使用生产环境对其进行基准测试:

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

它可能会改变您的状况。

+0

由于'3.0'会成为'rail benchmarker ...' – jibiel 2012-07-13 09:12:06

4

在开发模式下,每个查询计时并记录在日志/ development.log最简单的方法。你必须像线:

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

报告数据库服务器部件上的实际查询时间。它不测量ORM的工作,比如为每条记录创建一堆对象。 – 2014-03-15 12:23:30

28

这个问题有点老,需要更新的答案。在生产场景之外对查询进行基准测试的最简单方法是在rails console(基准测试脚本不在Rails中)中运行测试。然后,您可以使用内置于Ruby中的Benchmark类进行测试。运行Rails中的以下内容:

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

我运行的5倍以上,丢弃的最小值和最大值,并在剩下的三只奔跑的平均成本要弄清楚哪个查询会给你更好的性能。

这是自Rails doesn't show you the cost to actually construct your objects以来最准确的解决方案,可以获得真实查询的成本。因此,虽然@Slobodan Kovacevic答案是正确的,因为日志显示了查询如何进行记录,但long并不会为您的第二个查询提供更少的对象构建时间,因为您只填充单个字段与所有用户字段。