Created
May 27, 2014 13:18
-
-
Save nanaya/95bde0c601f3b50bf9d1 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env ruby | |
# encoding: utf-8 | |
# | |
# Idea from http://jsfiddle.net/G83mW/1/ | |
# (but less smart) | |
# | |
# Sparked off http://blogs.msdn.com/b/oldnewthing/archive/2014/05/26/10528351.aspx | |
# | |
require "benchmark" | |
def find_manual(arr) | |
lowest = arr[0] | |
arr[1..-1].each do |val| | |
lowest = val if val < lowest | |
end | |
lowest | |
end | |
def find_reduce(arr) | |
arr[1..-1].reduce(arr[0]) { |lowest, val| val < lowest ? val : lowest } | |
end | |
def find_native(arr) | |
arr.min | |
end | |
def rand_double(count) | |
count.times.map { rand } | |
end | |
def rand_int(count) | |
count.times.map { rand(count) } | |
end | |
[100_000, 200_000, 500_000, 1_000_000].each do |count| | |
arr_int = rand_int(count) | |
arr_double = rand_double(count) | |
[arr_int, arr_double].each do |arr| | |
puts ">>> Mode: #{count} / #{arr.first.class}" | |
puts "Manual: #{find_manual(arr)}" | |
puts "Reduce: #{find_reduce(arr)}" | |
puts "Native: #{find_native(arr)}" | |
Benchmark.bmbm do |x| | |
x.report("manual") { 1_000.times { find_manual(arr); } } | |
x.report("reduce") { 1_000.times { find_reduce(arr); } } | |
x.report("native") { 1_000.times { find_native(arr); } } | |
end | |
puts | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
JRuby 1.7