Skip to content

Instantly share code, notes, and snippets.

@jasonroelofs
Created January 16, 2009 16:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jasonroelofs/47992 to your computer and use it in GitHub Desktop.
Save jasonroelofs/47992 to your computer and use it in GitHub Desktop.
require 'benchmark'
N = 1_000_000
a = []
100.times { a << (rand(10) > 5 ? true : false) }
Benchmark.bm(20) { |x|
x.report("String#to_i(base)") {
N.times { a.map {|v| v ? "1" : "0" }.join().to_i(2) }
}
x.report("Bit shift") {
N.times { tmp = 0; a.each {|v| tmp |= (v ? 1 : 0); tmp <<= 1}; tmp >>= 1 }
}
}
=begin
roelofs@trillian ~/tmp $ ruby test.rb
user system total real
String#to_i(base) 51.880000 0.130000 52.010000 ( 54.645228)
Bit shift 151.350000 0.400000 151.750000 (159.552085)
=end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment