expression.py 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. # Benchmark to compare the times for computing expressions by using
  2. # ctable objects. Numexpr is needed in order to execute this.
  3. import math
  4. from time import time
  5. import numpy as np
  6. import numexpr as ne
  7. import bcolz
  8. N = 1e7 # the number of elements in x
  9. clevel = 3 # the compression level
  10. # sexpr = "(x+1)<0" # the expression to compute
  11. #sexpr = "(2*x**3+.3*y**2+z+1)<0" # the expression to compute
  12. sexpr = "((.25*x + .75)*x - 1.5)*x - 2" # a computer-friendly polynomial
  13. #sexpr = "(((.25*x + .75)*x - 1.5)*x - 2)<0" # a computer-friendly polynomial
  14. print("Creating inputs...")
  15. cparams = bcolz.cparams(clevel)
  16. x = np.arange(N)
  17. #x = np.linspace(0,100,N)
  18. cx = bcolz.carray(x, cparams=cparams)
  19. if 'y' not in sexpr:
  20. t = bcolz.ctable((cx,), names=['x'])
  21. else:
  22. y = np.arange(N)
  23. z = np.arange(N)
  24. cy = bcolz.carray(y, cparams=cparams)
  25. cz = bcolz.carray(z, cparams=cparams)
  26. t = bcolz.ctable((cx, cy, cz), names=['x', 'y', 'z'])
  27. print("Evaluating '%s' with 10^%d points" % (sexpr, int(math.log10(N))))
  28. t0 = time()
  29. out = eval(sexpr)
  30. print("Time for plain numpy--> %.3f" % (time() - t0,))
  31. t0 = time()
  32. out = ne.evaluate(sexpr)
  33. print("Time for numexpr (numpy)--> %.3f" % (time() - t0,))
  34. # Uncomment the next for disabling threading
  35. #ne.set_num_threads(1)
  36. #bcolz.blosc_set_nthreads(1)
  37. # Seems that this works better if we dividw the number of cores by 2.
  38. # Maybe due to some contention between Numexpr and Blosc?
  39. #bcolz.set_nthreads(bcolz.ncores//2)
  40. for kernel in "python", "numexpr":
  41. t0 = time()
  42. #cout = t.eval(sexpr, kernel=kernel, cparams=cparams)
  43. cout = t.eval(sexpr, cparams=cparams)
  44. print("Time for ctable (%s) --> %.3f" % (kernel, time() - t0,))
  45. #print "cout-->", repr(cout)
  46. #assert_array_equal(out, cout, "Arrays are not equal")