Created
August 8, 2010 00:09
-
-
Save sial-ari/513370 to your computer and use it in GitHub Desktop.
This file contains 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" | |
require "inline" | |
class Integer | |
def count_set_bits(use_c = false) | |
return csb(self) if use_c | |
return 0 if self.zero? | |
bits, x = 1, self | |
bits += 1 while (x = x & (x - 1)).nonzero? | |
bits | |
end | |
inline do |builder| | |
builder.c "int csb(long x) { | |
if (x == 0) return (x); | |
int bits = 1; | |
while ((x = x & (x - 1))) bits++; | |
return (bits); | |
}" | |
end | |
end | |
Benchmark.bmbm do |b| | |
b.report("ruby") { 100_000.times { 152363.count_set_bits } } | |
b.report("c") { 100_000.times { 152363.count_set_bits(true) } } | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment