Skip to content

Instantly share code, notes, and snippets.

@jamielennox
Created September 21, 2016 02:00
Show Gist options
  • Select an option

  • Save jamielennox/cbe229f88b9667b8ae2cb587da5f99ca to your computer and use it in GitHub Desktop.

Select an option

Save jamielennox/cbe229f88b9667b8ae2cb587da5f99ca to your computer and use it in GitHub Desktop.

Revisions

  1. jamielennox created this gist Sep 21, 2016.
    73 changes: 73 additions & 0 deletions arraytime.py
    Original 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