Skip to content

Instantly share code, notes, and snippets.

@kryzhovnik
Created August 9, 2020 21:25
Show Gist options
  • Save kryzhovnik/288953a5c89df10e2611668703a1511c to your computer and use it in GitHub Desktop.
Save kryzhovnik/288953a5c89df10e2611668703a1511c to your computer and use it in GitHub Desktop.
require 'benchmark'
module Config
N = 50000
A_LENGTH = 100
B_LENGTH = 10
def self.generate_array(length)
(1..length).map { (rand * length).round }
end
end
def compare(a, b, &block)
a_then_b = Benchmark.realtime { Config::N.times { block.call(a, b) } }
b_then_a = Benchmark.realtime { Config::N.times { block.call(b, a) } }
((b_then_a - a_then_b) / b_then_a) * 100
end
puts "A is an array of #{Config::A_LENGTH} elements, B - #{Config::B_LENGTH} elements"
5.times {
a = Config.generate_array(Config::A_LENGTH)
b = Config.generate_array(Config::B_LENGTH)
percent = compare(a, b) { |a, b| a | b }
puts "(A | B) is #{percent.round}% faster then (B | A)"
}
5.times {
a = Config.generate_array(Config::A_LENGTH)
b = Config.generate_array(Config::B_LENGTH)
percent = compare(a, b) { |a, b| a & b }
puts "(A & B) is #{percent.round}% faster then (B & A)"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment