Created
September 21, 2016 02:00
-
-
Save jamielennox/cbe229f88b9667b8ae2cb587da5f99ca to your computer and use it in GitHub Desktop.
Revisions
-
jamielennox created this gist
Sep 21, 2016 .There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,73 @@ 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