Advertisement
makispaiktis

Execution time about for-loops in Python

Jul 29th, 2020 (edited)
2,342
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.70 KB | None | 0 0
  1. from timeit import default_timer as timer
  2.  
  3. # 1a. For-loop
  4. position1 = 0
  5. start = timer()
  6. for i in range(1, 10**10):
  7.     end = timer()
  8.     elapsedTimeInMilliseconds = 1000 * (end - start)
  9.     if elapsedTimeInMilliseconds >= 1000:
  10.         position1 = i
  11.         break
  12.  
  13.  
  14. # 1b. Second for-loop
  15. position2 = 0
  16. start = timer()
  17. for i in range(1, 10**10):
  18.     end = timer()
  19.     elapsedTimeInMilliseconds = 1000 * (end - start)
  20.     if elapsedTimeInMilliseconds >= 2000:
  21.         position2 = i
  22.         break
  23.  
  24.  
  25. # 2a. For-loop with conditions
  26. position3 = 0
  27. start = timer()
  28. for i in range(1, 10**10):
  29.     if i < 0 or i > 10**10:
  30.         print("Error")
  31.     end = timer()
  32.     elapsedTimeInMilliseconds = 1000 * (end - start)
  33.     if elapsedTimeInMilliseconds >= 1000:
  34.         position3 = i
  35.         break
  36.  
  37.  
  38. # 2b. Second for-loop with conditions
  39. position4 = 0
  40. start = timer()
  41. for i in range(1, 10**10):
  42.     if i < 0 or i > 10**10:
  43.         print("Error")
  44.     end = timer()
  45.     elapsedTimeInMilliseconds = 1000 * (end - start)
  46.     if elapsedTimeInMilliseconds >= 2000:
  47.         position4 = i
  48.         break
  49.  
  50.  
  51. # MAIN FUNCTION
  52. percentage1 = (position1 - position3) / position1
  53. percentage2 = (position2 - position4) / position2
  54. percentage1 = int(10000 * percentage1) / 10000
  55. percentage2 = int(10000 * percentage2) / 10000
  56. print("******** Execution time = 1 second ********")
  57. print(str(position1) + " simple iterations")
  58. print(str(position3) + " iterations with conditions (" + str(100*percentage1) + "% less)")
  59. print()
  60. print("******** Execution time = 2 seconds ********")
  61. print(str(position2) + " simple iterations")
  62. print(str(position4) + " iterations with conditions (" +  str(100*percentage2) + "% less)")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement