fork(1) download
  1. # your code goes here
  2.  
  3. import timeit
  4.  
  5. setup1 = """
  6. import numpy as np
  7.  
  8. def my_unit_circle(r):
  9. d = 2*r + 1
  10. rx, ry = d/2, d/2
  11. x, y = np.indices((d, d))
  12. return (np.abs(np.hypot(rx - x, ry - y) - r) < 0.5).astype(int)
  13. """
  14.  
  15. setup2 = """
  16. import numpy as np
  17.  
  18. def unit_circle_vectorized(r):
  19. A = np.arange(-r,r+1)**2
  20. dists = np.sqrt(A[:,None] + A)
  21. return (np.abs(dists-r)<0.5).astype(int)
  22. """
  23.  
  24. print(timeit.timeit("my_unit_circle(100)", setup=setup1, number=100))
  25. print(timeit.timeit("unit_circle_vectorized(100)", setup=setup2, number=100))
  26.  
  27.  
  28.  
  29.  
Success #stdin #stdout 0.3s 25384KB
stdin
Standard input is empty
stdout
0.146565198898
0.104187011719