[Tutor] stop a loop after precise amount of time
Steven D'Aprano
steve at pearwood.info
Sun Nov 25 10:57:34 CET 2012
On 25/11/12 19:50, Saad Javed wrote:
> import time
>
> s = time.time() + 30
> running = True
> while running:
> if time.time() == s:
> print 'yes'
> running = False
>
> This stops the loop after 30s but the program uses about 12% cpu. What
> would be a more efficient way to do this? (p.s. i'm on python 2.7.3)
import time
time.sleep(30)
print "Done sleeping"
By the way, if you decide to use a while loop, don't test for time == s
exactly. If the timer misses your target by even a billionth of a second,
the loop will never end. Better is:
stop = time.time() + 30
while time.time() < stop:
pass
print "Done"
but don't do this either, use time.sleep.
--
Steven
More information about the Tutor
mailing list