Skip to content

Instantly share code, notes, and snippets.

@worace
Created February 9, 2015 22:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save worace/88a241e6d41ca67efff0 to your computer and use it in GitHub Desktop.
Save worace/88a241e6d41ca67efff0 to your computer and use it in GitHub Desktop.
Benchmark Examples in Ruby
require "benchmark"
# Benchmark perf of array.find
array = (1..1_000_000).to_a
res = Benchmark.measure do
array.find { |i| i == (array.length - 3) }
end
puts "benchmarking finding element in an array of 1"
puts res
array = (1..10_000_000).to_a
res = Benchmark.measure do
array.find { |i| i == (array.length - 3) }
end
puts "benchmarking finding element in an array of 10mil"
puts res
hash = {}
puts "will add 1mil items to a hash"
1_000_000.times do |i|
hash[i.to_s] = i
end
res = Benchmark.measure do
hash.fetch(9009.to_s)
end
puts "benchmarking fetching element from a hash of 10"
puts res
puts "will add 10 items to a hash"
10.times do |i|
hash[i.to_s] = i
end
res = Benchmark.measure do
hash.fetch(9.to_s)
end
puts "benchmarking fetching element from a hash of 10"
puts res
puts "FILE IO"
res = Benchmark.measure do
File.read("/usr/share/dict/words")
end
puts "time to read FIle from file system"
puts res
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment