-
-
Save gaffneyc/47994 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'benchmark' | |
N = 100_000 | |
a = [] | |
100.times { a << (rand(10) > 5 ? true : false) } | |
Benchmark.bm(35) { |x| | |
x.report("String#to_i(base)") { | |
N.times { a.map {|v| v ? "1" : "0" }.join().to_i(2) } | |
} | |
x.report("String#to_i(base integers)") { | |
N.times { a.map {|v| v ? 1 : 0 }.join().to_i(2) } | |
} | |
x.report("Bit shift") { | |
N.times { a.inject(0) {|m, v| m <<= 1; m | (v ? 1 : 0) } } | |
} | |
# Precompute | |
a.map! {|v| v ? "1" : "0" } | |
x.report("String#to_i(premapped)") { | |
N.times { a.join().to_i(2) } | |
} | |
a.map! {|v| v.to_i } | |
x.report("Bit shift(premapped)") { | |
N.times { a.inject(0) {|m, v| m <<= 1; m | v } } | |
} | |
} | |
=begin | |
gaffneyc@magrathea ~/dev/git/47994 (master) $ ruby gistfile1.rb | |
user system total real | |
String#to_i(base) 4.950000 0.020000 4.970000 ( 5.004080) | |
String#to_i(base integers) 10.400000 0.050000 10.450000 ( 10.557950) | |
Bit shift 20.770000 0.090000 20.860000 ( 21.046028) | |
String#to_i(premapped) 1.040000 0.010000 1.050000 ( 1.064023) | |
Bit shift(premapped) 20.140000 0.090000 20.230000 ( 20.413547) | |
=end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment