2010-08-05 237 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並不會爲您的第二個查詢提供更少的對象構建時間,因爲您只填充單個字段與所有用戶字段。