fork(1) download
  1. import timeit
  2. import numpy as np
  3.  
  4. f = lambda x: x ** 2
  5. vf = np.vectorize(f)
  6.  
  7. def test_array(x, n):
  8. t = timeit.timeit(
  9. 'np.array([f(xi) for xi in x])',
  10. 'from __main__ import np, x, f', number=n)
  11. print('array: ' + str(t))
  12.  
  13. def test_fromiter(x, n):
  14. t = timeit.timeit(
  15. 'np.fromiter((f(xi) for xi in x), x.dtype, count=len(x))',
  16. 'from __main__ import np, x, f', number=n)
  17. print('fromiter: ' + str(t))
  18.  
  19. def test_vectorized(x, n):
  20. t = timeit.timeit(
  21. 'vf(x)',
  22. 'from __main__ import x, vf', number=n)
  23. print('vectorized: ' + str(t))
  24.  
  25. def test_direct(x, n):
  26. t = timeit.timeit(
  27. 'f(x)',
  28. 'from __main__ import x, f', number=n)
  29. print('direct: ' + str(t))
  30.  
  31. x = np.arange(1000)
  32. n = 1000
  33. test_array(x, n)
  34. test_fromiter(x, n)
  35. test_vectorized(x, n)
  36. test_direct(x, n)
Success #stdin #stdout 0.91s 93248KB
stdin
Standard input is empty
stdout
array: 0.27999582327902317
fromiter: 0.2506440319120884
vectorized: 0.3054586574435234
direct: 0.01562817022204399