Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- require 'benchmark'
- # Benchmarks for various array operations.
- #
- # user system total real
- # Array.new 0.570000 0.000000 0.570000 ( 0.572061)
- # [] 0.380000 0.000000 0.380000 ( 0.383014)
- # dup 0.560000 0.000000 0.560000 ( 0.554559)
- # replace 0.410000 0.000000 0.410000 ( 0.411269)
- # pack * 1.670000 0.000000 1.670000 ( 1.670611)
- # pack H40 1.740000 0.000000 1.740000 ( 1.752113)
- # pack H40*10 1.180000 0.000000 1.180000 ( 1.179426)
- #
- Benchmark.bm(20) do |x|
- n = 1000000
- a = [1,2,3]
- b = [4,5,6]
- x.report("Array.new") do
- n.times do
- Array.new
- end
- end
- x.report("[]") do
- n.times do
- []
- end
- end
- x.report("dup") do
- n.times do
- a.dup
- end
- end
- x.report("replace") do
- n.times do
- a.replace(b)
- end
- end
- x.report("pack *") do
- sha = "ee8b5c4ddb843673ef659cfebd0c9e4cbe8ca59d"
- a = [sha]
- n.times { a.pack("H*") }
- end
- x.report("pack H40") do
- sha = "ee8b5c4ddb843673ef659cfebd0c9e4cbe8ca59d"
- a = [sha]
- n.times { a.pack("H40") }
- end
- x.report("pack H40*10") do
- sha = "ee8b5c4ddb843673ef659cfebd0c9e4cbe8ca59d"
- a = Array.new(10, sha)
- (n/10).times { a.pack("H40" * 10) }
- end
- end
- # An interesting thing to note here is how the time for unshift 'exponentially'
- # increases with n. The other methods are more linear in time. Note too that
- # shift is faster than pop; ie a FIFO queue using push/shift is fastest.
- #
- # user system total real
- # push 10k 0.010000 0.000000 0.010000 ( 0.002962)
- # pop 10k 0.000000 0.000000 0.000000 ( 0.003004)
- # unshift 10k 0.040000 0.000000 0.040000 ( 0.041590)
- # shift 10k 0.000000 0.000000 0.000000 ( 0.002379)
- # user system total real
- # push 100k 0.030000 0.000000 0.030000 ( 0.027808)
- # pop 100k 0.030000 0.000000 0.030000 ( 0.025829)
- # unshift 100k 4.130000 0.020000 4.150000 ( 4.223530)
- # shift 100k 0.020000 0.000000 0.020000 ( 0.023153)
- # user system total real
- # push 1000k 0.280000 0.010000 0.290000 ( 0.278975)
- # pop 1000k 0.250000 0.000000 0.250000 ( 0.253572)
- # shift 1000k 0.220000 0.000000 0.220000 ( 0.219806)
- #
- [10, 100, 1000].each do |n|
- Benchmark.bm(20) do |x|
- m = n * 1000
- array = []
- x.report("push #{n}k") do
- m.times { array.push(nil) }
- end
- x.report("pop #{n}k") do
- m.times { array.pop }
- end
- x.report("unshift #{n}k") do
- m.times { array.unshift(nil) }
- end unless n > 100
- x.report("shift #{n}k") do
- m.times { array.shift }
- end
- end
- end
Add Comment
Please, Sign In to add comment