简体   繁体   中英

Running a python for loop iteration for 5 seconds

The following code runs the main() function and sleeps for exactly 5seconds - 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM