Aditya suresh
Aditya suresh

Reputation: 119

Running a python for loop iteration for 5 seconds

The following code runs the main function and sleeps for exactly 5 seconds - time spent to run the function.

starttime = time.time()
timeout = time.time() + 60 * 2  # 60 seconds times 2 meaning the script will run for 2 
                                # minutes
while time.time() <= timeout:
        main()
        time.sleep(5 - ((time.time() - starttime) % 5.0))  # 5 second interval between 
                                                           # each new iteration

I am not sure how the code

time.sleep(5 - ((time.time() - starttime) % 5.0))

ensures a 5 second interval.

Upvotes: 2

Views: 1318

Answers (1)

aichao
aichao

Reputation: 7435

The identified code ensures that main() is called every 5 seconds ONLY IF the execution of main() takes less than 5 seconds. This is because the modulo operator % in python computes the remainder of (time.time() - starttime) divide by 5.0 at each iteration of the while loop. This remainder is the execution time of main() in each iteration. Subtracting this from the 5 seconds gives a sleep time that result in the 5 second interval in calling main().

The assumption here is that the time to execute main() is significant compared to executing any other line of code shown here. Under this assumption, to see that the remainder of (time.time() - starttime) divide by 5.0 is the execution time of main(), consider:

  1. In the first iteration, (time.time() - starttime) is the time to execute main(), and if the execution of main() takes less than 5 seconds, this is the remainder when divided by 5.0.
  2. In the second iteration, (time.time() - starttime) is 5 seconds plus the time to execute main() in the second iteration because the sleep in the first iteration is such that 5.0 seconds elapsed between the calling of main() between the first and second iterations. Hence, the remainder of this divided by 5.0 is the time to execute main() in the second iteration.
  3. In subsequent iteration i, it is clear that (time.time() - starttime) is (i - 1) * 5 seconds plus the time to execute main() in the i-th iteration. Hence the argument from (2) holds for all iterations until the while loop exits.

Upvotes: 1

Related Questions