Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using NSTimer to get accurate timings

Tags:

cocoa

iphone

I need to run my game loop with very accurate timing. I am trying to use NSTimer to do this, and I am getting ok results, but there is a bit of drift. When NSTimer fires does the next time event start counting when the handler finishes or does it start counting straight away. If the former is it reasonable for me to use setFireDate to try to offset the next timer firing - when I tried this things seemed worse.

My timer is set to fire every 44ms and I would like to stop it drifting by more than 20ms. If it does drift I would like to correct it for the next fire. Is this a reasonable thing to try and do with NSTimer?

like image 217
Ian1971 Avatar asked Dec 28 '25 12:12

Ian1971


2 Answers

I don't think NSTimer will give you "very" accurate timing. It fires on the run loop, so if it's in your main thread then it'll get delayed by everything from UI updates to event handling.

like image 120
Daniel Dickison Avatar answered Dec 31 '25 07:12

Daniel Dickison


You might try creating a thread and scheduling your timer on that thread's run loop. Having that timer as the only thing on that run loop should limit the number of things that can interfere with it.

If that doesn't work, well, you'll already have it working on a thread, so you may as well switch to a usleep() loop.

like image 25
Peter Hosey Avatar answered Dec 31 '25 07:12

Peter Hosey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!