fork download
  1. import time, random, heapq
  2.  
  3. class Timer:
  4. def __init__(self, description):
  5. self.description = description
  6.  
  7. def __enter__(self):
  8. self.start = time.perf_counter()
  9. return self
  10.  
  11. def __exit__(self, *args):
  12. end = time.perf_counter()
  13. print(f"The time for {self.description} took: {end - self.start}.")
  14.  
  15.  
  16. def f3(x,k): # O(N) Time | O(N) Storage
  17. y = []
  18. idx=0
  19. while idx<k:
  20. curr_min = min(x)
  21. x.remove(curr_min)
  22. y.append(curr_min)
  23. idx += 1
  24. return y
  25.  
  26.  
  27. def f_heap(x, k): # O(nlogn)
  28. heapq.heapify(x)
  29. return [heapq.heappop(x) for _ in range(k)]
  30.  
  31.  
  32.  
  33. N=1000000
  34. x = [random.randint(0,N) for i in range(N)]
  35.  
  36. TRIALS = 1
  37.  
  38. with Timer('f3') as t:
  39. for _ in range(TRIALS):
  40. y = f3(x.copy(), 10)
  41. print(y)
  42.  
  43. print()
  44.  
  45. with Timer('f_heap') as t:
  46. for _ in range(TRIALS):
  47. y = f_heap(x.copy(), 10)
  48. print(y)
Success #stdin #stdout 1.3s 58976KB
stdin
Standard input is empty
stdout
The time for f3 took: 0.21665403246879578.
[0, 1, 3, 7, 8, 9, 9, 10, 11, 12]

The time for f_heap took: 0.04939376190304756.
[0, 1, 3, 7, 8, 9, 9, 10, 11, 12]