3

I am writing an iPhone game. When the user makes his first move a timer kicks of with an interval of 0.01 seconds. A UILabel displaying the time also gets updated every time. I noticed when testing on an iPod touch 2nd gen and an iPhone 3GS that the iPod was slower (after 20 seconds the iPhone displayed 00:20,00 and the iPod displayed ~00:10,00). Is there a way to make this more reliable? If I'm correct, the NSTimer should run on its ow thread and should not be blocked by user interaction.

JNK

JNK
  • 1,753
  • 8
  • 25
  • 37

3 Answers3

3

The NSTimer documentation states:

Because of the various input sources a typical run loop manages, the effective resolution of the time interval for a timer is limited to on the order of 50-100 milliseconds. If a timer’s firing time occurs while the run loop is in a mode that is not monitoring the timer or during a long callout, the timer does not fire until the next time the run loop checks the timer. Therefore, the actual time at which the timer fires potentially can be a significant period of time after the scheduled firing time.

So accuracy can be as bad as 0.1, not 0.01 seconds. Not to mention if your thread is blocked for some reason. So if your firing time is crucial you should be looking at other things. Read this SO post for kick-off. Apple had a metronome sample code (in which, obviously, timing is crucial) but I can't find it just now.

In any case, if you are implementing a timer with NSTimer, you should record your start time. Then, whenever you update your interface, simply take the difference of the current time and your start time (with NSDates).

Community
  • 1
  • 1
jbat100
  • 16,757
  • 4
  • 45
  • 70
0

make sure you're not basing a timer off of sleeps or delays. You should always update a timer based on things like number of clock ticks since program start or current time

sorry I'm not more familiar with your language

user980058
  • 511
  • 7
  • 18
0

You can't rely on a timer to run exactly at the specified time intervals, so the time you are displaying should always be calculated by taking time interval differences. And I doubt that a timer on the iPhone can run every 1 ms, in Quartz it is possible to get a timer call every 16 ms or so, making 60 fps - so scheduling it at 1ms probably means "run as soon as possible", which might be quite different on different hardware.

TheEye
  • 9,280
  • 2
  • 42
  • 58