Skip to content

Instantly share code, notes, and snippets.

@wmayner
Created April 25, 2014 21:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wmayner/11303323 to your computer and use it in GitHub Desktop.
Save wmayner/11303323 to your computer and use it in GitHub Desktop.
Python: timing various ways of flipping bits in a binary string
#!/env/sh
# Test various ways of flipping '1's and '0's in a Python binary string.
TEST="'111101111010001000100100001'"
TESTINT="129831201"
echo "Bit manipulation given decimal int:"
PYSTRING="i = $TESTINT; bin((i ^ (2 ** (i.bit_length()+1) - 1)))[3:]"
echo "$PYSTRING\n"
python -m timeit "$PYSTRING"
echo "\nBit manipulation given string:"
PYSTRING="s = $TEST; bin((int(s, 2) ^ (2**(len(s)+1) - 1)))[3:]"
echo "$PYSTRING\n"
python -m timeit "$PYSTRING"
echo "\nSequential str.replace:"
PYSTRING="s = $TEST; s.replace('1', '2').replace('0', '1').replace('2', '0')"
echo "$PYSTRING\n"
python -m timeit "$PYSTRING"
echo "\nstr.maketrans:"
PYSTRING="s = $TEST; s.translate(str.maketrans('10', '01'))"
echo "$PYSTRING\n"
python -m timeit "$PYSTRING"
echo "\n''.join with dictionary mapping:"
PYSTRING="s = $TEST; flip = {'1':'0', '0':'1'}; ''.join(flip[b] for b in s)"
echo "$PYSTRING\n"
python -m timeit "$PYSTRING"
echo "\n''.join with conditional:"
PYSTRING="s = $TEST; ''.join('1' if b == '0' else '0' for b in s)"
echo "$PYSTRING\n"
python -m timeit "$PYSTRING"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment