[Tutor] iteration controll.

Magnus Lycka magnus@thinkware.se
Wed, 28 Aug 2002 14:12:29 +0200


At 22:41 2002-08-28 +1200, Thomi Richards wrote:
>I have made a program which needs to iterate through an instruction set
>at a user defined speed. The user doesn't need to know exactly what the
>numbers are, they just have a slider with faster at one end, and slower
>at the other. So say the speed range goes from 1 iteration a second
>(slowest) to 80 iterations a second (fastest). I'm still not sure what
>the fastest speed will be for this computer, and of course this will
>change from system to system. anyway, the problem is that i cannot think
>of how to add a delay command to the code, to adjust the speeds
>accordingly. what i need is something which says in python "if this code
>block takes longer then <usertime>, decrease the delay, if it took less
>than <usertime>, increase the delay". any idea?
>
>ideally that block of code should only run if the program senses that
>the timings are out, so it doesn't slow the program down all the time.

"import time" is a start...

"time.sleep(x)" will make the program sleep for x seconds, where x
is a float.

"time.time()" gives the number of seconds since new-year 1970 as a float.

delay =3D 1.0 / iter_per_sec

while something:
   # Here we start measuring
   start =3D time.time()
   # Here is the code which should run at a certain interval.
   ...
   # Check whether we should delay
   elapsed =3D time.time() - start
   if elapsed < delay:
     time.sleep(delay - elapsed)

Be sure not to execute time.sleep() with a negative time...


--=20
Magnus Lyck=E5, Thinkware AB
=C4lvans v=E4g 99, SE-907 50 UME=C5
tel: 070-582 80 65, fax: 070-612 80 65
http://www.thinkware.se/  mailto:magnus@thinkware.se