Skip to content

Instantly share code, notes, and snippets.

@RespiteSage
Created April 7, 2021 22:05
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 RespiteSage/522ca15524dfc0a673d9d105da9c326b to your computer and use it in GitHub Desktop.
Save RespiteSage/522ca15524dfc0a673d9d105da9c326b to your computer and use it in GitHub Desktop.
Testing different nested min implementations against solutions for known number of dimensions
def recursive_min_flatten(arr)
# creates a flattened copy of the array and then finds the minimum
arr.flatten.min
end
def recursive_min_iterator(arr)
# creates an iterator of the array, adds flattening to the iterator, and then iterates to find the min
arr.each.flatten.min
end
require "benchmark"
# to try and manipulate the compiler into using all the benchmark code
min = 0
# 1D
puts "Benchmarking 1D array min"
Benchmark.ips do |x|
one_d = Array.new(1_000_000) { (1..1000).sample }
x.report("Array#min") do
min = one_d.min
end
x.report("recursive_min_flatten") do
min = recursive_min_flatten one_d
end
x.report("recursive_min_iterator") do
min = recursive_min_iterator one_d
end
end
puts "---\n"
puts "Benchmarking 2D array min"
Benchmark.ips do |x|
two_d = Array.new(1_000) { Array.new(1_000) { (1..1000).sample } }
x.report("Array#min_of(&.min)") do
min = two_d.min_of(&.min)
end
x.report("recursive_min_flatten") do
min = recursive_min_flatten two_d
end
x.report("recursive_min_iterator") do
min = recursive_min_iterator two_d
end
end
puts "---\n"
puts "Benchmarking 3D array min"
Benchmark.ips do |x|
three_d = Array.new(100) { Array.new(100) { Array.new(100) { (1..1000).sample } } }
x.report("Array#min_of(&.min_of(&.min))") do
min = three_d.min_of(&.min_of(&.min))
end
x.report("recursive_min_flatten") do
min = recursive_min_flatten three_d
end
x.report("recursive_min_iterator") do
min = recursive_min_iterator three_d
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment