Guest User

Untitled

a guest
Dec 16th, 2018
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.38 KB | None | 0 0
  1. import math
  2. import time
  3. import random
  4.  
  5.  
  6. def find_dist_squared(x1, y1, x2, y2):
  7. return (x2 - x1) ** 2 + (y2 - y1) ** 2
  8.  
  9.  
  10. def find_dist_squared_v2(x1, y1, x2, y2):
  11. dx = x2 - x1
  12. dy = y2 - y1
  13. return dx * dx + dy + dy
  14.  
  15.  
  16. def find_dist(x1, y1, x2, y2):
  17. return math.hypot(x1 - x2, y1 - y2)
  18.  
  19.  
  20. def time_function_10000_times(func, name):
  21. start = time.clock()
  22.  
  23. for _ in range(10000):
  24. func()
  25.  
  26. elapsed = time.clock()
  27. elapsed = elapsed - start
  28. print ("Time spent in " + name + " is: " + str(elapsed))
  29.  
  30.  
  31. def find_dist_squared_impl():
  32. return find_dist_squared(0, 0, random.random(), random.random())
  33.  
  34.  
  35. def find_dist_squared_v2_impl():
  36. return find_dist_squared_v2(0, 0, random.random(), random.random())
  37.  
  38.  
  39. def find_dist_impl():
  40. return find_dist(0, 0, random.random(), random.random())
  41.  
  42.  
  43. time_function_10000_times(find_dist_impl, "find dist")
  44. time_function_10000_times(find_dist_squared_impl, "find dist squared")
  45. time_function_10000_times(find_dist_squared_v2_impl, "find dist squared v2")
  46.  
  47. """
  48. Time spent in find dist is: 0.005446
  49. Time spent in find dist squared is: 0.005252
  50. Time spent in find dist squared v2 is: 0.004622
  51.  
  52. Process finished with exit code 0
  53. """
Add Comment
Please, Sign In to add comment