eval.py 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. # Benchmark to compare the times for computing expressions by using
  2. # eval() on carray/numpy arrays. Numexpr is needed in order to
  3. # execute this.
  4. from __future__ import print_function
  5. import math
  6. from time import time
  7. import numpy as np
  8. import numexpr as ne
  9. import bcolz
  10. N = 1e7 # the number of elements in x
  11. clevel = 9 # the compression level
  12. sexprs = ["(x+1)<0",
  13. "(2*x**2+.3*y**2+z+1)<0",
  14. "((.25*x + .75)*x - 1.5)*x - 2",
  15. "(((.25*x + .75)*x - 1.5)*x - 2)<0",
  16. ]
  17. # Initial dataset
  18. # x = np.arange(N)
  19. x = np.linspace(0, 100, N)
  20. doprofile = False
  21. def compute_ref(sexpr):
  22. t0 = time()
  23. out = eval(sexpr)
  24. print("Time for plain numpy --> %.3f" % (time() - t0,))
  25. t0 = time()
  26. out = ne.evaluate(sexpr)
  27. print("Time for numexpr (numpy) --> %.3f" % (time() - t0,))
  28. def compute_carray(sexpr, clevel, vm):
  29. # Uncomment the next for disabling threading
  30. # Maybe due to some contention between Numexpr and Blosc?
  31. # bcolz.set_nthreads(bcolz.ncores//2)
  32. print("*** carray (using compression clevel = %d):" % clevel)
  33. if clevel > 0:
  34. x, y, z = cx, cy, cz
  35. t0 = time()
  36. cout = bcolz.eval(sexpr, vm=vm, cparams=bcolz.cparams(clevel))
  37. print("Time for bcolz.eval (%s) --> %.3f" % (vm, time() - t0,), end="")
  38. print(", cratio (out): %.1f" % (cout.nbytes / float(cout.cbytes)))
  39. #print "cout-->", repr(cout)
  40. if __name__ == "__main__":
  41. print("Creating inputs...")
  42. cparams = bcolz.cparams(clevel)
  43. y = x.copy()
  44. z = x.copy()
  45. cx = bcolz.carray(x, cparams=cparams)
  46. cy = bcolz.carray(y, cparams=cparams)
  47. cz = bcolz.carray(z, cparams=cparams)
  48. for sexpr in sexprs:
  49. print("Evaluating '%s' with 10^%d points" % (
  50. sexpr, int(math.log10(N))))
  51. compute_ref(sexpr)
  52. for vm in "python", "numexpr":
  53. compute_carray(sexpr, clevel=0, vm=vm)
  54. if doprofile:
  55. import pstats
  56. import cProfile as prof
  57. #prof.run('compute_carray(sexpr, clevel=clevel, vm="numexpr")',
  58. prof.run('compute_carray(sexpr, clevel=0, vm="numexpr")',
  59. #prof.run('compute_carray(sexpr, clevel=clevel,
  60. # vm="python")',
  61. #prof.run('compute_carray(sexpr, clevel=0, vm="python")',
  62. 'eval.prof')
  63. stats = pstats.Stats('eval.prof')
  64. stats.strip_dirs()
  65. stats.sort_stats('time', 'calls')
  66. stats.print_stats(20)
  67. else:
  68. for vm in "python", "numexpr":
  69. compute_carray(sexpr, clevel=clevel, vm=vm)