Skip to content

Instantly share code, notes, and snippets.

@jasonroelofs
Created January 16, 2009 16:46

Revisions

  1. jameskilton created this gist Jan 16, 2009.
    26 changes: 26 additions & 0 deletions gistfile1.rb
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,26 @@
    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