spacepaste

  1.  
  2. """
  3. homer pypy $ /tmp/download/pypy2-v5.7.1-linux64/bin/pypy benchstruct.py
  4. unpack str: 0.05 secs
  5. unpack bytearray: 0.24 secs
  6. unpack array: 0.34 secs
  7. unpack np.array: 2.52 secs
  8. plan pack: 2.56 secs
  9. pack_into bytearray: 0.36 secs
  10. homer pypy $ pypy benchstruct.py
  11. unpack str: 0.05 secs
  12. unpack bytearray: 0.16 secs
  13. unpack array: 0.18 secs
  14. unpack np.array: 0.23 secs
  15. plan pack: 2.12 secs
  16. pack_into bytearray: 0.06 secs
  17. """
  18. import struct
  19. import array
  20. import _numpypy.multiarray as np
  21. import time
  22. N = 10000000
  23. BUF_STR = [struct.pack('qq', 1, 2), struct.pack('qq', 3, 4)]
  24. BUF_BA = map(bytearray, BUF_STR)
  25. BUF_ARRAY = [array.array('b', buf) for buf in BUF_STR]
  26. BUF_NP = [np.array([1, 2]), np.array([3, 4])]
  27. def bench_unpack(title, LST):
  28. res = 0
  29. a = time.time()
  30. for i in range(N):
  31. buf = LST[i%2]
  32. val = struct.unpack('qq', buf)[0]
  33. res += val
  34. b = time.time()
  35. print '%20s: %.2f secs' % (title, b-a)
  36. return res
  37. def bench_pack():
  38. lst = [None]*N
  39. buf = struct.pack('q', 4)
  40. a = time.time()
  41. for i in range(N):
  42. buf = struct.pack('q', i)
  43. lst[i] = buf
  44. b = time.time()
  45. print '%20s: %.2f secs' % ('plan pack', b-a)
  46. def bench_pack_into():
  47. lst = [bytearray(8)]*N
  48. a = time.time()
  49. for i, buf in enumerate(lst):
  50. struct.pack_into('q', buf, 0, i)
  51. b = time.time()
  52. print '%20s: %.2f secs' % ('pack_into bytearray', b-a)
  53. def main():
  54. bench_unpack('unpack str', BUF_STR)
  55. bench_unpack('unpack bytearray', BUF_BA)
  56. bench_unpack('unpack array', BUF_ARRAY)
  57. bench_unpack('unpack np.array', BUF_NP)
  58. bench_pack()
  59. bench_pack_into()
  60. main()
  61.