[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)

Benchmark.realtime

想要獲取花費時間,客制化信息

1
2
3
4
require 'benchmark'

result = Benchmark.realtime { create_object(10_000_000) }
puts "Creating ten million objects: #{result.round(2)}s"

output:

1
Creating ten million objects: 1.27s

Benchmark.bm

計算多個 ruby several blocks 比較

1
2
3
def sort_array
(1..1000000).map { rand }
end
1
2
3
4
5
6
require 'benchmark'

Benchmark.bm(5) do |x|
x.report("sort!") { sort_array.dup.sort! }
x.report("sort") { sort_array.dup.sort }
end

我研究許久,發現 (5) 竟然只是 label 至表格的距離
就只是格式而已…

1
2
3
            user     system      total        real
sort! 0.860000 0.010000 0.870000 ( 0.874565)
sort 0.870000 0.010000 0.880000 ( 0.879724)

Benchmark.bmbm

複雜的回收處裡等,計算兩次可以使用
These differences are due to the cost of memory allocation and garbage collection

1
2
3
4
5
6
require 'benchmark'

Benchmark.bmbm do |x|
x.report("sort!") { sort_array.dup.sort! }
x.report("sort") { sort_array.dup.sort }
end

output:

1
2
3
4
5
6
7
8
Rehearsal -----------------------------------------
sort! 0.870000 0.010000 0.880000 ( 0.877750)
sort 0.870000 0.010000 0.880000 ( 0.884924)
-------------------------------- total: 1.760000sec

user system total real
sort! 0.880000 0.010000 0.890000 ( 0.894623)
sort 0.890000 0.010000 0.900000 ( 0.898280)

Benchmark.benchmark

假設需要比較後的平均花費時間、總共時間,可以這麼處裡:

1
2
3
4
5
6
7
8
9
10
require 'benchmark'
include Benchmark # we need the CAPTION and FORMAT constants

num = 5000000
Benchmark.benchmark(CAPTION, 7, "111%r", ">total:", ">avg:") do |x|
tf = x.report("for:") { for i in 1..num; a = "1"; end }
tt = x.report("times:") { num.times do ; a = "1"; end }
tu = x.report("upto:") { 1.upto(num) do ; a = "1"; end }
[tf+tt+tu, (tf+tt+tu)/3]
end

output:

1
2
3
4
5
6
              user     system      total        real
for: 0.350000 0.000000 0.350000 ( 0.349957)
times: 0.340000 0.000000 0.340000 ( 0.341593)
upto: 0.340000 0.010000 0.350000 ( 0.348147)
>total: 1.030000 0.010000 1.040000 ( 1.039697)
>avg: 0.343333 0.003333 0.346667 ( 0.346566)

Ref

其他相關應用

Comments

Your browser is out-of-date!

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

×