-2

I need two timers in my game one counting in seconds and the other in milliseconds. I had 2 labels, functions and variables. First function with interval 1.0 and the other with 0.001. But the 0.001 timer is always slower than 1.0 (for example 700ms and 1s). How can I fix it?

rmaddy
  • 314,917
  • 42
  • 532
  • 579
  • 3
    Expecting anything to execute reliably at 1KHz on a non-hard-real-time OS is to invite disappointment. – ipmcc Aug 30 '13 at 01:49
  • yet, 700 ms in 1 sec. is way out of tolerance even @1KHz ... unless, user2719716, you accumulated these totals over a few minutes, and shown us only the average bad result. If so, then ipmcc has solved your problem. – Howard Pautz Aug 30 '13 at 02:10

3 Answers3

2

You should never assume that a timer triggered at N milliseconds will be called at exactly that interval.

Timers are designed to trigger after a wait of at least N milliseconds, and due to thread priorities it will almost certainly trigger after a longer wait.

Also, if you're processing something that takes longer than a millisecond in the timer trigger, you'll essentially 'skip' some triggers and get the lower value that you describe.

To get the time elapsed, use date differences, not timer counters.

Getting the time elapsed (Objective-c)

Community
  • 1
  • 1
Josh B
  • 1,748
  • 16
  • 19
  • Ok let's assume that i need stopwatch instead of a timer. And I need him to show 1000 milliseconds after a second. What should i do then? – user2719716 Aug 30 '13 at 01:51
  • When you start the 'stopwatch' save the date time, then on every invocation of the timer, check how many milliseconds have elapsed by comparing the saved time to 'now'. Display this value, and stop or do whatever once it's > 1000. – Josh B Aug 30 '13 at 01:53
0

hmmm ... why not just use one timer and tick 1k ms. for a sec. ? set flag, call func. etc. I can't think of a good reason to ever need more than one timer (except for micro controllers servicing hardware, but clearly that's not what you're doing).

Howard Pautz
  • 415
  • 7
  • 21
  • That is not the problem. The problem is that when 1k ms passes actually passes more than 1 second. – user2719716 Aug 30 '13 at 01:44
  • 2
    on both timers ??? which version of iOS and what device are you using ? Perhaps you'd better post your code - this one needs to be replicated. (Hard to believe that what you're saying is happening ! But I do give you the benefit of the doubt. We can be more helpful always with code. – Howard Pautz Aug 30 '13 at 02:07
0

Why are you counting seconds? Should you not calculate the time based on the difference between the clock start and the current clock? This would make the timers match since they would be from the same reference. It sounds like you are actually counting based on a timer task. This will make the accrued time vary dependent on thread execution, etc.

Centijo
  • 584
  • 6
  • 15