Amir Shabani
Amir Shabani

Reputation: 4207

Using time.time() in while loop causes function to be called twice

I created a function like this:

import time

def func(seconds):
    time.sleep(seconds)
    print(f'waited {seconds} seconds')

Now if I create a while loop like this and call func(6), after 6 seconds, it will print waited 6 seconds:

start_time = time.time()
while time.time() - start_time < 5:
    func(6)

output:
waited 6 seconds

But if I create the same while loop, while calling func(4), the script will wait 4 seconds, then print waited 4 seconds and after 4 seconds, it will print waited 4 seconds again!

start_time = time.time()

while time.time() - start_time < 5:
    func(4)

output:
waited 4 seconds
waited 4 seconds

Why does this happen?

I understand why func(6) behaves like that, but I expected that func(4) would be executed only once, thus printing waited 4 seconds only once.

Upvotes: 0

Views: 494

Answers (3)

nalamrc
nalamrc

Reputation: 11

The while condition (< 5) against the time-delta calculation would allow the while loop to enter again after 4 sec sleep, example the new time delta might be 4.0022xxx post the first 4 sec sleep, since the condition (4.0022xx < 5) is True, it will lead to second 4 sec sleep.

Upvotes: 0

Patrick Artner
Patrick Artner

Reputation: 51683

What happens:

start_time = time.time()               # captures the time right now()
while time.time() - start_time < 5:    # 1.) checks the time right after last check
                                       # 3.) checks the time right after 6s passed
    func(6)                            # 2.) waits 6 seconds
                                       # 4.) done

When you use 4s:

start_time = time.time()               # captures the time right now()
while time.time() - start_time < 5:    # 1.) checks the time right after last check
                                       # 3.) checks the time right after 4s passed, still < 5
                                       #     (should be something along 4.00023 or so)
                                       # 5.) checks the time afte4 4+4s passed
    func(4)                            # 2.) waits 4 seconds
                                       # 4.) waits 4 more seconds
                                       # 6.) done

Subtracting times gives you a float:

import time

t = time.time()
time.sleep(1)           # guaranteed to wait at least 1s
print(time.time()-t)  

Output:

1.00106596947

After time.sleep(4) you are still far away from 5 - which is the reason that it enters the loop twice.

Upvotes: 1

Simon
Simon

Reputation: 5698

The while conditions checks if five seconds have passed. For func(6), "6 seconds > 5 seconds", so the condition is met and it ends the while loop. When func(4) returns, the condition is "4 seconds > 5 seconds" is not True, so the while loop will iterate once more.

Upvotes: 2

Related Questions