0
import time
stop_time = time.time() + 5 #5 seconds
while time.time() < stop_time:
    for i in range(1000000):
        print(i)
        for x in range(654165):
            print(x)

How to stop this loop after 5 seconds?

1 Answers1

1

You can use the perf_counter() method:

import time

while time.perf_counter() <= 5:
    for i in range(1000000):
        if time.perf_counter() <= 5:
            print(i)
            for x in range(654165):
                if time.perf_counter() <= 5:
                    print(x)
Red
  • 26,798
  • 7
  • 36
  • 58
  • Thanks for the valuable suggestion. I don't think the execution occurs. Also I am using Python 3.7.4 (64 bit). –  Jun 04 '20 at 15:36