Reputation: 827
I have for loop and I need each iteration to take exactly 5 milliseconds. i.e 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
Upvotes: 0
Views: 81
Reputation: 8972
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.
Upvotes: 1