4

I need to run a loop during a precise duration. For example, the code I'm trying to make would look like that :

initialize and lauch timer

while timer<10000sec:
   do things

Do you know how to do this ?

Thank you :)

4
  • Should do things be aborted after given time or should it finish first? Commented Dec 29, 2010 at 10:28
  • The whole "Do thing" have to be done, so it must not be aborted at the end of the timer. Commented Dec 29, 2010 at 10:36
  • Just how precise do you have to be, and why? Commented Dec 29, 2010 at 13:13
  • I have to be precise around the second (plus the time of an occurence of the loop). This code is made to test the capacity of a server, so the precision is not critical. Commented Dec 29, 2010 at 18:07

2 Answers 2

6
stop = time.time()+10000
while time.time() < stop:
  do things

This requires that each run through the loop is sufficiently short so that you read the current time often enough (for the preciseness that you want to achieve).

Sign up to request clarification or add additional context in comments.

3 Comments

on the other hand if the loop body is very short the call to time.time() on each iteration can dominate the runtime. What I'm trying to say to the OP is that if performance is critical here, he may consider an alternative approach
This code works perfectly. But I'd like a method less power consuming if it exists.
@Nix: you'll have to explain what "do things" actually is. In good programming, you should be blocking when you wait for something to happen, instead of polling: this (bad) approach is called "busy wait". If you need busy wait, you can put calls of time.sleep(delay) into the loop, with delay being e.g. 0.2.
1
import time

t_end = time.time() + 60 * <> #duration goes inside <>; eg 2 for 2 minutes

while time.time() < t_end:

   #rest of the code

1 Comment

Remember that Stack Overflow isn't just intended to solve the immediate problem, but also to help future readers find solutions to similar problems, which requires understanding the underlying code. This is especially important for members of our community who are beginners, and not familiar with the syntax. Given that, can you edit your answer to include an explanation of what you're doing and why you believe it is the best approach?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.