我重讀基準文檔,發現它有一個名爲measure
方法。這種方法不正是我想要的東西:測量你的代碼所需要的時間和返回包含用戶時間的對象,系統時間,兒童等的系統時間,它是那麼容易,因爲
require 'benchmark'
measurement = Benchmark.measure do
# your code goes here
end
在這個過程中,我發現您可以將自定義行添加到Benchmark輸出。你可以用它來獲得兩全其美(自定義時間的測量,並在年底一個不錯的輸出)如下:
require 'benchmark'
measurements = []
10.times { measurements << Benchmark.measure { 1_000_000.times { a = "1" } } }
# measurements.sum or measurements.inject(0){...} does not work, since the
# array contains Benchmark instances, which cannot be coerced into Fixnum's
# Array#sum will work if you are using Rails
sum = measurements.inject(nil) { |sum, t| sum.nil? ? sum = t : sum += t }
avg = sum/measurements.size
# 7 is the width reserved for the description "sum:" and "avg:"
Benchmark.bm(7, "sum:", "avg:") do |b|
[sum, avg]
end
結果將如下所示:
user system total real
sum: 2.700000 0.000000 2.700000 ( 2.706234)
avg: 0.270000 0.000000 0.270000 ( 0.270623)
我只希望有'require'基準測試的快捷方式; Benchmark.measure {...}' – dolzenko 2013-12-25 18:57:38
我不明白,引用的部分很短。你想要點什麼? (Pseduo代碼允許;) – 2013-12-28 23:23:46
當然,可能不會比這更短,只是感嘆缺乏一些默認提供的快捷鍵以保存輸入。 +我總是忘記它是'measure'還是'bm'或'bmbm'或其他東西:) – dolzenko 2013-12-30 13:47:13