Skip to content

Instantly share code, notes, and snippets.

@whartonn
Created April 7, 2013 14:47
Show Gist options
  • Save whartonn/5330780 to your computer and use it in GitHub Desktop.
Save whartonn/5330780 to your computer and use it in GitHub Desktop.
mod-based even/odd vs bit-based even/odd
def odd_or_even_mod(number)
return "Even" if number % 2 == 0
return "Odd"
end
def odd_or_even_bit(number)
return "Even" if number & 1 == 0
return "Odd"
end
require 'benchmark'
Benchmark.bm(40) do |x|
x.report ('mod even/odd') do
100_000.times do
odd_or_even_mod(948479784)
odd_or_even_mod(948479785)
end
end
x.report('bitwise even/odd') do
100_000.times do
odd_or_even_bit(948479784)
odd_or_even_bit(948479785)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment