Skip to content

Instantly share code, notes, and snippets.

@jamielennox
Created September 21, 2016 02:00
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 jamielennox/cbe229f88b9667b8ae2cb587da5f99ca to your computer and use it in GitHub Desktop.
Save jamielennox/cbe229f88b9667b8ae2cb587da5f99ca to your computer and use it in GitHub Desktop.
import array
import timeit
import numpy
import sys
mask = [0x71, 0x45, 0x54, 0x82]
mask_str = ''.join(chr(m) for m in mask)
def time_numpy(data):
plen = len(data)
b = c = ''
if plen >= 4:
dtype=numpy.dtype('<u4')
if sys.byteorder == 'big':
dtype = dtype.newbyteorder('>')
mask = numpy.fromstring(mask_str, dtype)
data = numpy.frombuffer(data, dtype, count=int(plen / 4))
b = numpy.bitwise_xor(data, mask).tostring()
if plen % 4:
dtype = numpy.dtype('B')
if sys.byteorder == 'big':
dtype = dtype.newbyteorder('>')
mask = numpy.fromstring(mask_str, dtype, count=(plen % 4))
data = numpy.frombuffer(buf, dtype,
offset=plen - (plen % 4), count=(plen % 4))
c = numpy.bitwise_xor(data, mask).tostring()
return b + c
def time_array(data):
a = array.array('B')
a.fromstring(data)
for i in range(len(data)):
a[i] ^= mask[i % 4]
return a.tostring()
def time_bytearray(data):
a = bytearray(data)
for i in range(len(a)):
a[i] ^= mask[i % 4]
return a.decode('latin-1')
def wrapper(func, *args, **kwargs):
def wrapped():
return func(*args, **kwargs)
return wrapped
if __name__ == '__main__':
with open('/dev/urandom', 'r') as f:
data = f.read(4096 * 16)
for func in (time_array, time_bytearray, time_numpy):
print timeit.timeit(wrapper(func, data), number=1000)
# Results:
# 13.1004390717
# 11.6302118301
# 0.0161831378937
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment