-
- """
- homer pypy $ /tmp/download/pypy2-v5.7.1-linux64/bin/pypy benchstruct.py
- unpack str: 0.05 secs
- unpack bytearray: 0.24 secs
- unpack array: 0.34 secs
- unpack np.array: 2.52 secs
- plan pack: 2.56 secs
- pack_into bytearray: 0.36 secs
- homer pypy $ pypy benchstruct.py
- unpack str: 0.05 secs
- unpack bytearray: 0.16 secs
- unpack array: 0.18 secs
- unpack np.array: 0.23 secs
- plan pack: 2.12 secs
- pack_into bytearray: 0.06 secs
- """
-
- import struct
- import array
- import _numpypy.multiarray as np
- import time
-
- N = 10000000
- BUF_STR = [struct.pack('qq', 1, 2), struct.pack('qq', 3, 4)]
- BUF_BA = map(bytearray, BUF_STR)
- BUF_ARRAY = [array.array('b', buf) for buf in BUF_STR]
- BUF_NP = [np.array([1, 2]), np.array([3, 4])]
-
-
- def bench_unpack(title, LST):
- res = 0
- a = time.time()
- for i in range(N):
- buf = LST[i%2]
- val = struct.unpack('qq', buf)[0]
- res += val
- b = time.time()
- print '%20s: %.2f secs' % (title, b-a)
- return res
-
- def bench_pack():
- lst = [None]*N
- buf = struct.pack('q', 4)
- a = time.time()
- for i in range(N):
- buf = struct.pack('q', i)
- lst[i] = buf
- b = time.time()
- print '%20s: %.2f secs' % ('plan pack', b-a)
-
-
- def bench_pack_into():
- lst = [bytearray(8)]*N
- a = time.time()
- for i, buf in enumerate(lst):
- struct.pack_into('q', buf, 0, i)
- b = time.time()
- print '%20s: %.2f secs' % ('pack_into bytearray', b-a)
-
- def main():
- bench_unpack('unpack str', BUF_STR)
- bench_unpack('unpack bytearray', BUF_BA)
- bench_unpack('unpack array', BUF_ARRAY)
- bench_unpack('unpack np.array', BUF_NP)
- bench_pack()
- bench_pack_into()
-
- main()
-