Skip to content

Instantly share code, notes, and snippets.

@xcombelle
Created May 22, 2015 13:34
Show Gist options
  • Save xcombelle/565627839bcc0ecdd0ec to your computer and use it in GitHub Desktop.
Save xcombelle/565627839bcc0ecdd0ec to your computer and use it in GitHub Desktop.
super bit count
setup = """
def bitcount (n):
c = 0
while n > 0:
n, r = divmod(n, 2)
c += r
return c
def fact(size):
bc = [bitcount(i) for i in range(2**(size))]
mask = 2**(size)-1
def sbc(n):
assert n>0
c = 0
while n>0:
#print(c,hex(n))
c+=bc[n&mask]
n>>=size
return c
return sbc
sbc= fact(8)
"""
exec(setup)
#print (bitcount(2**29-1))
#print(sbc(2**29-1))
import timeit
print(timeit.timeit("bitcount(2**29 - 1)",setup=setup,number=10**5))
print(timeit.timeit("sbc(2**29 - 1)",setup=setup,number=10**5))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment