Last active
August 29, 2015 14:03
-
-
Save leepro/88ccdacf7b6026367957 to your computer and use it in GitHub Desktop.
Counting bits (4bytes integer)
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
| # coding: utf-8 | |
| # In[196]: | |
| import timeit | |
| # In[197]: | |
| codebook = [ bin(_).count("1") for _ in xrange(0xff) ] | |
| # In[198]: | |
| def only_codebook(n): | |
| if n <= 0xff: | |
| return codebook[n] | |
| elif n <= 0xffff: | |
| return codebook[n & 0xff] + codebook[ n>>8 ] | |
| elif n <= 0xffffff: | |
| return codebook[n & 0xff] + codebook[ (n>>8) & 0xff ] + codebook[ (n>>16) & 0xff ] | |
| else: | |
| return codebook[n & 0xff] + codebook[ (n>>8) & 0xff ] + codebook[ (n>>16) & 0xff ] + codebook[ (n>>24) & 0xff ] | |
| # In[199]: | |
| def only_bitshift(n): | |
| c = 0 | |
| for _ in xrange(32): | |
| if n & 1 == 1: | |
| c+=1 | |
| n = n >> 1 | |
| return c | |
| # In[200]: | |
| def mix_codebook_bitshift(n): | |
| c = 0 | |
| for _ in xrange(4): | |
| c+=codebook[n&0xff] | |
| n = n >> 8 | |
| return c | |
| # In[201]: | |
| def bin2stringcount(n): | |
| return bin(n).count("1") | |
| def and_plus(n): | |
| c = 0 | |
| while n: | |
| n&=n-1 | |
| c+=1 | |
| return c | |
| # In[202]: | |
| N = 0xffff+3 | |
| # In[207]: | |
| get_ipython().magic(u'timeit bin2stringcount(N)') | |
| # In[208]: | |
| get_ipython().magic(u'timeit only_codebook(N)') | |
| # In[209]: | |
| get_ipython().magic(u'timeit only_bitshift(N)') | |
| # In[210]: | |
| get_ipython().magic(u'timeit mix_codebook_bitshift(N)') | |
| # In[211]: | |
| get_ipython().magic(u'timeit and_plus(N)') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment