get the flagged bit index in pure python
<p>i involve here 2 questions: one is for 'how', and second is for 'is this great solution sounds ok?'<br>
the thing is this: i have an object with int value that stores all the persons' ids that used that object. it's done using a flagging technique (person id is 0-10).  </p>

<p>i got to a situation where in case this value is flagged with only one id, i want to get this id.  </p>

<p>for the first test i used <code>value &amp; (value-1)</code> which is nice, but as for the second thing, i started to wonder what's the best way to do it (the reason i wonder about it is because this calculation happens at least 300 times in a second in a critical place).  </p>

<p>so the 1st way i thought about is using <code>math.log(x,2)</code>, but i feel a little uncomfortable with this solution since it involves "hard" math on a value, instead of very simple bits operation, and i feel like i'm missing something.  </p>

<p>the 2nd way i thought about is to count <code>value&lt;&lt;1</code> until it reaches 1, but it as you could see in the benchmark test, it was just worse.  </p>

<p>the 3rd way i was implemented is a non-calc way, and was the fastest, and it's using a dictionary with all the possible values for ids 0-10.</p>

<p>so like i said before: is there a 'right' way for doing it in <strong>pure</strong> python?<br>
is a dictionary-based solution is a "legitimate" solution? (readability/any-other-reason-why-not-to?)  </p>

<pre><code>import math
import time

def find_bit_using_loop(num,_):
    c=0
    while num!=1:
        c+=1
        num=num&gt;&gt;1
    return c

def find_bit_using_dict(num,_):
    return options[num]

def get_bit_idx(num, func):
    t=time.time()
    for i in xrange(100000):
        a=func(num,2)
    t=time.time()-t
    #print a
    return t

options={}
for i in xrange(20):
    options[1&lt;&lt;i]=i

num=256
print "time using log:", get_bit_idx(num, math.log)
print "time using loop:", get_bit_idx(num, find_bit_using_loop)
print "time using dict:", get_bit_idx(num, find_bit_using_dict)
</code></pre>

<p>output:</p>

<pre><code>time using log: 0.0450000762939
time using loop: 0.156999826431
time using dict: 0.0199999809265
</code></pre>

<p>(there's a very similar question here: <a href="http://stackoverflow.com/questions/5520655/return-index-of-least-significant-bit-in-python">return index of least significant bit in Python</a> , but first, in this case i know there's only 1 flagged bit, and second, i want to keep it a pure python solution)</p>
