fromiter.py 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. # Benchmark for assessing the `fromiter()` speed.
  2. from time import time
  3. import numpy as np
  4. from numpy.testing import assert_array_equal
  5. import bcolz
  6. from bcolz.py2help import xrange, izip
  7. N = int(1e6) # the number of elements in x
  8. clevel = 2 # the compression level
  9. print("Creating inputs with %d elements..." % N)
  10. x = xrange(N) # not a true iterable, but can be converted
  11. y = xrange(1, N + 1)
  12. z = xrange(2, N + 2)
  13. print("Starting benchmark now for creating arrays...")
  14. # Create a ndarray
  15. # x = (i for i in xrange(N)) # true iterable
  16. t0 = time()
  17. out = np.fromiter(x, dtype='f8', count=N)
  18. print("Time for array--> %.3f" % (time() - t0,))
  19. print("out-->", len(out))
  20. #bcolz.set_num_threads(bcolz.ncores//2)
  21. # Create a carray
  22. #x = (i for i in xrange(N)) # true iterable
  23. t0 = time()
  24. cout = bcolz.fromiter(x, dtype='f8', count=N, cparams=bcolz.cparams(clevel))
  25. print("Time for carray--> %.3f" % (time() - t0,))
  26. print("cout-->", len(cout))
  27. assert_array_equal(out, cout, "Arrays are not equal")
  28. # Create a carray (with unknown size)
  29. #x = (i for i in xrange(N)) # true iterable
  30. t0 = time()
  31. cout = bcolz.fromiter(x, dtype='f8', count=-1, cparams=bcolz.cparams(clevel))
  32. print("Time for carray (count=-1)--> %.3f" % (time() - t0,))
  33. print("cout-->", len(cout))
  34. assert_array_equal(out, cout, "Arrays are not equal")
  35. # Retrieve from a structured ndarray
  36. gen = ((i, j, k) for i, j, k in izip(x, y, z))
  37. t0 = time()
  38. out = np.fromiter(gen, dtype="f8,f8,f8", count=N)
  39. print("Time for structured array--> %.3f" % (time() - t0,))
  40. print("out-->", len(out))
  41. # Retrieve from a ctable
  42. gen = ((i, j, k) for i, j, k in izip(x, y, z))
  43. t0 = time()
  44. cout = bcolz.fromiter(gen, dtype="f8,f8,f8", count=N)
  45. print("Time for ctable--> %.3f" % (time() - t0,))
  46. print("out-->", len(cout))
  47. assert_array_equal(out, cout[:], "Arrays are not equal")
  48. # Retrieve from a ctable (with unknown size)
  49. gen = ((i, j, k) for i, j, k in izip(x, y, z))
  50. t0 = time()
  51. cout = bcolz.fromiter(gen, dtype="f8,f8,f8", count=-1)
  52. print("Time for ctable (count=-1)--> %.3f" % (time() - t0,))
  53. print("out-->", len(cout))
  54. assert_array_equal(out, cout[:], "Arrays are not equal")