Now I want to compute at how many of the L
positions in the binary representation there is a 1
as well as a zero 0
. In my example the result would be return=2
since there is always a 1
in the third (last) position for these entries. I want to compute this inside a function with a numba decoratorI want to compute this inside a function with a numba decorator.
Currently my code is:
Comparing the performance:
def count_mixed_bits_timeit():
lst = [random.randint(0, 500) for i in range(10000)]
for _ in range(300):
xor = reduce(and_, lst) ^ reduce(or_, lst)
retu = bin(xor).count("1")
return retu
@nb.njit
def count_mixed_bits_v2_timeit():
lst = [random.randint(0, 500) for i in range(10000)]
for _ in range(300):
andnumber = ornumber = lst[0]
for value in lst:
andnumber &= value
ornumber |= value
xornumber = andnumber ^ ornumber
result = 0
while xornumber > 0:
result += xornumber & 1
xornumber >>= 1
return result
@nb.njit
def count_mixed_bits_v3_timeit():
lst = [random.randint(0, 500) for i in range(10000)]
for _ in range(300):
and_, or_ = ~0, 0
for x in lst:
and_ &= x
or_ |= x
xor_ = and_ ^ or_
result = 0
while xor_ > 0:
result += 1
xor_ &= xor_ - 1
return result
print(timeit(lambda: count_mixed_bits_timeit(), number=10))
print(timeit(lambda: count_mixed_bits_v2_timeit(), number=10))
print(timeit(lambda: count_mixed_bits_v3_timeit(), number=10))
>>>2.4878
>>>0.1198
>>>0.1279