毫秒计时器? [英] Millisecond timer?

查看:43
本文介绍了毫秒计时器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有谁知道如何制作一个时间间隔为0.001的计时器?我在某处读到 Timer 的时间间隔不能低于 0.02,而我的计时器就是这样运行的.

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.

我的计时器:

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

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

推荐答案

是的,时间间隔可以小于 0.02 秒.例如.0.01 秒的间隔很容易实现.但在 0.001 或 0.0001 秒时,您开始受到在这段时间内可以完成多少实际考虑的限制.

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.

但如果您的目标是在 UI 中呈现某些内容,那么超过设备的最大每秒帧数(通常为 60 fps)几乎没有任何意义.如果屏幕只能每 60 秒更新一次,那么比这更频繁地计算有什么意义呢?那只是浪费了 CPU 周期.顺便说一句,如果我们试图实现最佳屏幕刷新率,我们会使用 CADisplayLink,而不是 Timer.它的工作原理与计时器类似,但它的最佳时间是以最佳速度刷新屏幕.

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.)

相反,如果我们想在我们的 UI 中尽可能快地更新,我们会保存开始时间,启动一个 CADisplayLink,并且每次调用计时器处理程序时,计算经过的时间作为当前时间和开始时间之间的差异.

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.

现在,如果你真的需要一个非常精确的计时器,它可以做到,但你应该看到 技术说明 TN2169,展示了如何创建高精度计时器.但这更像是一种边缘情况.

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.

这篇关于毫秒计时器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆