This page contains automated test results for code from O'Reilly's Ruby Cookbook. If this code looks interesting or useful, you might want to buy the whole book.
Benchmarking Competing Solutions | ||
---|---|---|
Code | Expected | Actual |
RANGE = (0..1000) array = RANGE.to_a hash = RANGE.inject({}) { |h,i| h[i] = true; h } def test_member?(data) RANGE.each { |i| data.member? i } end require 'benchmark' Benchmark.bm(5) do |timer| timer.report('Array') { test_member?(array) } timer.report('Hash') { test_member?(hash) } end |
user system total real Array 0.260000 0.060000 0.320000 ( 0.332583) Hash 0.010000 0.000000 0.010000 ( 0.001242) |
user system total real Array 0.280000 0.050000 0.330000 ( 0.318784) Hash 0.000000 0.000000 0.000000 ( 0.001216) |
Benchmark.bm(5) do |timer| timer.report('Array') { 1000.times { RANGE.each { |i| array[i] } } } timer.report('Hash') { 1000.times { RANGE.each { |i| hash[i] } } } end |
user system total real Array 0.950000 0.210000 1.160000 ( 1.175042) Hash 1.010000 0.210000 1.220000 ( 1.221090) |
user system total real Array 1.000000 0.180000 1.180000 ( 1.220659) Hash 1.060000 0.170000 1.230000 ( 1.252879) |
def write_to_file File.open('out', 'w') { |f| f.write('a') } end puts Benchmark.measure { 10000.times { write_to_file } } |
0.120000 0.360000 0.480000 ( 0.500653) |
0.130000 0.360000 0.490000 ( 0.499884) |