Last active
August 29, 2015 14:10
-
-
Save jrunning/7168af45c5fa5fb4ddd3 to your computer and use it in GitHub Desktop.
Benchmark checking columnwise equality in two-dimensional arrays
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
require "benchmark/ips" | |
ARRAY_SIZE = 5 # 5 rows and 5 columns | |
CHANCE = 0.33 | |
# Returns the given 5-element array with a 33% chance of one item being changed | |
def dirty_row(row) | |
return row if rand > CHANCE | |
row.dup.tap { row[rand 0..(ARRAY_SIZE - 1)] = rand 0..99 } | |
end | |
# Returns a 5x5 array in which each value is equal to the other values in the | |
# same "column", but some values may be randomly changed | |
def rand_5x5 | |
col_vals = Array.new(ARRAY_SIZE) { rand 0..99 } | |
Array.new(ARRAY_SIZE) { dirty_row(col_vals) } | |
end | |
# 3.times { puts rand_5x5.map {|row| row.map {|n| "%4i" % n }.join }; puts } | |
# Generate 100 random 5x5 arrays | |
testcases = Array.new(100) { rand_5x5 } | |
def meth_a(arr) | |
first_row, *rest = arr | |
rest.all? do |row| | |
row.each_with_index.all? do |item, col_idx| | |
row[col_idx] == first_row[col_idx] | |
end | |
end | |
end | |
def meth_b(arr) | |
arr.transpose.all? {|row| row.uniq.size == 1 } | |
end | |
Benchmark.ips do |x| | |
x.report("meth_a") { testcases.each {|testcase| meth_a(testcase) } } | |
x.report("meth_b") { testcases.each {|testcase| meth_b(testcase) } } | |
x.compare! | |
end |
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
Calculating ------------------------------------- | |
meth_a 410 i/100ms | |
meth_b 302 i/100ms | |
------------------------------------------------- | |
meth_a 4118.8 (±1.7%) i/s - 20910 in 5.078154s | |
meth_b 3089.2 (±2.7%) i/s - 15704 in 5.087200s | |
Comparison: | |
meth_a: 4118.8 i/s | |
meth_b: 3089.2 i/s - 1.33x slower |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment