[Tutor] Making a function run every second.
d at davea.name
Tue Nov 29 18:46:40 CET 2011
On 11/29/2011 11:09 AM, Dave Angel wrote:
> On 11/29/2011 10:52 AM, Mic wrote:
>> Okay, I undestand. Hmm, what is a drift?
I just noticed I hadn't answered that one. It doesn't matter any more
since you're running tkinter.
But for completeness:
If you had a non-event driven program (eg. a console app), and you had a
loop like the following:
SLEEPTIME = 1
myfunc() would be called about once a second. However, in a heavily
loaded system, it might be 1.2 seconds one time, and 1.1 the next. So
it might be called only 50 times in that minute, rather than 60. I
believe that in some OS's, it might be called 75 times in a minute.
Anyway, if drift is to be avoided, you need to keep track of the time
that the next call should be made, compare it to "now", and calculate
what to pass as a parameter to sleep().
In untested approx. code,
starttime = float(now())
SLEEPTIME = 1 (for one second)
for intervalnum in itertools.count():
delayneeded = starttime + SLEEPTIME*intervalnum - now()
if this drifts, it tries to compensate on the next iteration. Note that
there are cleverer implementations of this fundamental scheme, depending
on other requirements or goals.
More information about the Tutor