Millisecond timer?

半城伤御伤魂 提交于 2021-01-29 13:46:22

问题


Does anyone know how to make a timer with a time interval of 0.001? I read somewhere that a Timer can't have a time interval lower than 0.02, and my timer is behaving that way.

My timer:

timer = Timer.scheduledTimer(timeInterval: 0.001, target: self, selector: #selector(self.updateTimer), userInfo: nil, repeats: true)

@objc func updateTimer() {
   miliseconds += 0.001
}

回答1:


Yes, you can have time intervals less than 0.02 seconds. E.g. 0.01 second interval is easily accomplished. But at 0.001 or 0.0001 seconds, you’re starting to be constrained by practical considerations of how much you could accomplish in that period of time.

But if your goal is to represent something in the UI, there’s rarely any point for exceeding the device’s maximum frames per second (usually 60 fps). If the screen can only be updated every 60th of a second, what’s the point in calculating more frequently than that? That’s just wasted CPU cycles. By the way, if we were trying to achieve optimal screen refresh rates, we’d use CADisplayLink, not Timer. It works just like a timer, but is optimally timed for refreshing the screen at its optimal rate.

For what it’s worth, the idea of updating milliseconds to capture elapsed time is a bit of non-starter. We never update a “elapsed time counter” like this, because even in the best case scenarios, the frequency is not guaranteed. (And because of limitations in binary representations of fractional decimal values, we rarely want to be adding up floating point values like this, either.)

Instead, if we want to have the fastest possible updates in our UI, we’d save the start time, start a CADisplayLink, and every time the timer handler is called, calculate the elapsed time as the difference between current time and the start time.

Now, if you really needed a very precise timer, it can be done, but you should see Technical Note TN2169, which shows how to create high precision timer. But this is more of an edge-case scenario.




回答2:


Short answer: You can't do that. On iOS and Mac OS, Timers are invoked by your app's run loop, and only get invoked when your app visits the main event loop. How often a short-interval timer actually fires will depend on how much time your app spends serving the event loop. As you say, the docs recommend a minimum interval of about 1/50th of a second.

You might look at using a CADisplayLink timer, which is tied to the display refresh. Those timers need to run fast in order to not interfere with the operation of your app.

Why do you think you need a timer that fires exactly every millisecond?



来源:https://stackoverflow.com/questions/61232102/millisecond-timer

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!