简体   繁体   中英

Wait if code execution finished before a time limit and abort if didn't finish within limit

I have for loop and I need each iteration to take exactly 5 milliseconds. ie if the code finishes before the 5 milliseconds the iteration should wait until the 5 milliseconds pass, and if it takes more than 5 milliseconds the loop should ignore it and go to next iteration.

I tried this code but it is not accurate and it doesn't help to abort to next iteration if it takes more time

import time

for i in range(N):
    now = time.time_ns()
    do_something(i)
    time.sleep(0.005 - (time.time_ns() - now -3)*1e-9)

I used time_ns() as I assumed it would be more accurate than time() but it didn't help much

Save init time at the beginning

and use in your computations. Here's my example

import random
import time

N = 10
D = 0.5
T0 = time.time()

def do_something(msg):
    """Sleep 0 to 1 seconds"""
    time.sleep(random.random())
    print(msg)

for i in range(N):
    # check if we're overtime
    if T0 + (i+1)*D < time.time():
        continue

    do_something(i)

    # use modulo to compute sleep duration
    time.sleep(
        D - (time.time() - T0) % D
    )

And the output. Notice some numbers are missing and that it takes 10×0.5 = 5 seconds.

$ time python3 aly.py 
0
1
3
5
6
8

real    0m5.030s
user    0m0.028s
sys     0m0.004s

About time_ns : time.sleep needs float , so using integer nanoseconds is meaningless.

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