且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用Swift将实时秒表计时器格式化为百分之一

更新时间:2023-09-12 11:34:58

要快速更新UI,您应该使用

For rapid UI updates you should use a CADisplayLink. Anything faster than the display refresh rate is a waste of processing power since it physically cannot be displayed. It also provides a timestamp of the previous frame so you can try to predict when the next frame will be.

您要多次计算CACurrentMediaTime() - timerStarted + elapsedTime.我建议只执行一次并将其保存在本地变量中.

You're calculating CACurrentMediaTime() - timerStarted + elapsedTime multiple times. I would recommend doing it only once and saving it in a local variable.

考虑使用 NSDateComponentsFormatter .尝试重用格式化程序的一个实例,而不是每次都创建一个新的(通常是最昂贵的部分).总体而言,您可以执行的字符串操作越少越好.

Consider using NSDateComponentsFormatter. Try to reuse one instance of the formatter rather than creating a new one each time (which is usually the most expensive part). Overall, the less string manipulation you can do, the better.

您可以在显示方法的开始和结束处检查CACurrentMediaTime,以查看需要花费多长时间.理想情况下,它应该小于16.6毫秒.密切注意Xcode调试导航器中的CPU使用率(和一般功耗).

You can check CACurrentMediaTime at the beginning and end of your display method to see how long it takes. Ideally it should be much less than 16.6ms. Keep an eye on the CPU usage (and general power consumption) in the Xcode debug navigator.