Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
require 'benchmark/ips'
my_array = [100, 101, 100, 102, 100, 100, 101, 100, 250, 251, 253, 260, 250, 200, 100, 100, 100, 100, 100, 100, 100, 100, 100, 120]
index_and_repetitions = lambda { |my_array|
stk = {}
previous = my_array[0]
last_index = 0
stk[last_index] = 1
my_array.drop(0).each_with_index do |item, index|
if item == previous
stk[last_index] += 1
else
last_index = index
stk[last_index] = 1
previous = item
end
end
stk
}
Benchmark.ips do |x|
x.time = 5
x.warmup = 2
x.report('oshanz') do |_t|
stk = index_and_repetitions.call(my_array)
stk.key(stk.values.max)
end
x.report('cary') do |_t|
my_array.each_index.chunk { |i| my_array[i] }
.max_by { |_, a| a.size }
.last
.first
end
x.report('zhou') do |_t|
my_array.index.with_index { |_value, index| my_array[index, 6].uniq.size == 1 }
end
x.report('ray') do |_t|
groups = my_array[1..-1].each_with_object([[my_array[0]]]) { |n, m| m.last[0] == n ? m.last << n : m << [n]; }
groups[0, groups.index(groups.max_by(&:count))].flatten.count
end
x.compare!
end
@oshanz

This comment has been minimized.

Copy link
Owner Author

oshanz commented Jan 15, 2019

Warming up --------------------------------------

           oshanz    10.471k i/100ms
            cary     4.771k i/100ms
            zhou     5.868k i/100ms
             ray     5.741k i/100ms

Calculating -------------------------------------

           oshanz      1.147B (±17.8%) i/s -      5.022B in   4.721988s
            cary    245.846M (±27.1%) i/s -      1.057B in   4.860784s
            zhou    373.943M (±22.9%) i/s -      1.652B in   4.856765s
             ray    330.414M (±21.7%) i/s -      1.471B in   4.836672s

Comparison:

             oshanz: 1147085295.2 i/s
            zhou: 373943146.9 i/s - 3.07x  slower
             ray: 330413853.0 i/s - 3.47x  slower
            cary: 245845639.8 i/s - 4.67x  slower
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.