Skip to content

Instantly share code, notes, and snippets.

@ggggggggg
Created September 30, 2014 23:08
Show Gist options
  • Save ggggggggg/392a8f7b25c1e9f6475d to your computer and use it in GitHub Desktop.
Save ggggggggg/392a8f7b25c1e9f6475d to your computer and use it in GitHub Desktop.
faster bit transitions
import bitarray
import time
import numpy as np
a = np.arange(100000, dtype=np.uint64)
def transitions(a):
b = bitarray.bitarray()
b.frombytes(a.tostring())
c=b.itersearch(bitarray.bitarray("01"))
return [d for d in c]
def find_01_bit_transitions(bitvector, nbits=64, prev_trig_state=False):
'''Given a vector of bits, return an array of sample numbers in which a 0->1
bit transition occurred. It is assumed that only the lowest <nbits> bits in
each data value need to be checked.
Here, "sample number" means row number. We're assuming that <nbits> is equal
to the number of rows in the data stream. The sample numbers will be with respect
to the first frame in the bitvector.
'''
transitions = []
fully_on = 0
for _ in range(nbits):
fully_on = (fully_on<<1) | 1
on_state = prev_trig_state
for i in xrange(len(bitvector)):
bp = int(bitvector[i])
if not on_state and (bp==0): continue
if on_state and (bp==fully_on): continue
for j in xrange(nbits):
thisbit = bool(bp & 1)
bp = bp>>1
if on_state != thisbit:
on_state = thisbit
if on_state:
rownum = j+(i*nbits)
transitions.append(rownum)
return transitions
t1 = time.time()
transitions(a)
t2 = time.time()
print(t2-t1) # 0.0973989963531
t1 = time.time()
find_01_bit_transitions(a)
t2 = time.time()
print(t2-t1) # 1.92169213295
@ggggggggg
Copy link
Author

sudo port install py27-bitarray to get the package
have I mentioned that I think package management in python is a clusterfuck after experiencing julia?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment