Note that there are some explanatory texts on larger screens.

plurals
  1. POiPhone - a question about dispatch timers and timing
    primarykey
    data
    text
    <p>I have to fire a method at regular intervals (every 0.16 seconds). The tolerance can be, lets say up to 30%. Closer to 16 ms, better.</p> <p>I have tried NSTimers but they are not precise enough. I have tried threads and also had the same problem. I am now trying dispatch timers.</p> <p>I am using this code provided by Apple:</p> <pre><code>dispatch_source_t CreateDispatchTimer(uint64_t interval, uint64_t leeway, dispatch_queue_t queue, dispatch_block_t block) { dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue); if (timer) { dispatch_source_set_timer(timer, dispatch_walltime(NULL, 0), interval, leeway); dispatch_source_set_event_handler(timer, block); dispatch_resume(timer); } return timer; } void MyCreateTimer() { dispatch_source_t aTimer = CreateDispatchTimer(0.16 * NSEC_PER_SEC, //0.16 ms 0.048 * NSEC_PER_SEC, //30% tolerance dispatch_get_main_queue(), ^{ MyPeriodicTask(); }); // Store it somewhere for later use. if (aTimer) { MyStoreTimer(aTimer); } } </code></pre> <p>I am measuring the intervals and getting these times between executions of MyPeriodicTask():</p> <pre><code>0.148, 0.165, 0.148, 0.167, 0.167, 0.187, 0.167, 0.167, 0.146, 0.166, 0.167, 0.167, 0.188, 0.145, 0.243, 0.331, 0.047, 0.045, 0.168, 0.165, 0.167, 0.166, 0.167, 0.167, 0.169, 0.165, 0.166, 0.169, 0.165, 0.203, 0.130, 0.167, 0.167, 0.167, 0.167, 0.167, 0.167, 0.167, 0.167, 0.167 </code></pre> <p>Notice that the method is being fired more or less within the 16ms range.</p> <p>considering the 30% range, I was expecting values between 0.118 and 0.214 ms, but notice values as 0.243 and 0.331 far above the range and others like 0.047 and 0.045!!!! How can the method fire before the timer interval???</p> <p>What can be happening? Is there a way to get precise execution of timed methods on iPhone???</p> <p>thanks.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload