Re: NSTimer fires ~0.0045 seconds early?
Re: NSTimer fires ~0.0045 seconds early?
- Subject: Re: NSTimer fires ~0.0045 seconds early?
- From: Brant Vasilieff <email@hidden>
- Date: Mon, 6 Aug 2001 09:23:57 -0700
On Monday, August 6, 2001, at 12:28 AM, Brendan Younger wrote:
I believe much of this is touched upon in the NSTimer docs. NSTimer
does not have perfect resolution since it adds itself to the current
run loop and the run loop is then responsible for calling the method.
Thus I believe that the NSTimer cheats a bit and sends the message
early so that it is sure to arrive in time. My suggestion is to test
for some interval of granularity when you schedule the timer so as to
avoid this problem.
According to the NSTimer docs:
"When the timer's time limit has elapsed, the NSRunLoop fires the timer
(causing its message to be sent), then checks for new input. Because of
the various input sources a typical run loop manages, the effective
resolution of the time interval for an NSTimer is limited to on the
order of 50-100 milliseconds."
I understand that because timers are fired from the run loop, that they
wouldn't be able to guarantee to fire exactly on time, and that there
would be a slight latency. What I wasn't expecting was for them to
cheat and fire early.
For the time being, I've added the 0.01 seconds of time to the interval
that I pass in. It seams to work, but I don't know what will happen on
a faster processor. It's a temporary fix, and I am in the middle of
finding a better solution for testing for the last event, but I thought
I'd point it out and see if anyone had any suggestions besides what I'm
doing.
I understand that fitting numbers into binary form can cause errors,
like 1 can sometimes be represented as 0.9999999999. So I suppose, I
can understand why the timer might fire 0.000000000001 or so early, but
I'm surprised with a double, that we get such poor accuracy, unless of
course they are cheating, and subtracting a constant. If so, I'd like
to know the constant is so I can add it back.
I also, notice that my timer always beats the clock in the menu bar by
about a half a second. Is that because they add 0.5 seconds to get past
this anomaly as well?
Cheers,
Brant