[Rails] Benchmark to test ruby code performance

當兩個相近的方法,該選擇哪一種效能比較好?
一般開發者在網路上查到結果就照著使用,沒有特別理解佐證的過程
所以來分享佐證的好工具:
benchmark - 為 Ruby Standard Library

Benchmark.measure

計算單獨的 ruby single block

1
2
3
4
5
def create_object(n)
n.times do
Object.new
end
end
1
2
3
require 'benchmark'

puts Benchmark.measure { create_object(10_000_000) }

output:

1
2
    user     system      total        real
1.270000 0.010000 1.280000 ( 1.272028)
Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×