max, sort :
require 'fruity'
ary = (1..100).to_a.shuffle
def use_max(a)
a.max(3).last
end
def use_sort(a)
a.sort[-3]
end
def nth_greatest(nums, n)
nums = nums.dup
result = nil
n.times do
idx, max = -1, -Float::INFINITY
nums.length.times do |i|
idx, max = [i - 1, nums[i - 1]] if nums[i - 1] > max
end
result = nums.delete_at idx
end
result
end
compare do
sorted { use_sort(ary) }
maxed { use_max(ary) }
nth_greatested { nth_greatest(ary, 3) }
end
:
ary = (1..1_000).to_a.shuffle
:
# >> Running each test 64 times. Test will take about 1 second.
# >> maxed is faster than sorted by 80.0% ± 10.0%
# >> sorted is faster than nth_greatested by 3x ± 0.1
:
ary = (1..10_000).to_a.shuffle
:
# >> Running each test 8 times. Test will take about 1 second.
# >> maxed is faster than sorted by 3x ± 0.1
# >> sorted is faster than nth_greatested by 2x ± 0.1
, max (3) , .
:
a.max(2) #=> ["horse", "dog"]
, , :
ary.max(3) # => [100, 99, 98]
Benchmark :
require 'benchmark'
ary = (1..5).to_a.shuffle
10.times do
Benchmark.bm(4) do |b|
b.report('sort') { ary.sort[-3] }
b.report('max') { ary.max(3).last }
end
end
:
ary = (1..100).to_a.shuffle
:
ary = (1..1_000).to_a.shuffle