high precision timer in Swift

半腔热情 提交于 2019-12-22 06:46:55

问题


What would be the best solution in Swift for a precise clock to control external hardware? I need to write a loop function that would fire at a set rate per second (hundreds or thousands Hz) reliably and with high precision.


回答1:


You can define a GCD timer property (because unlike NSTimer/Timer, you have to maintain your own strong reference to the GCD timer):

var timer: DispatchSourceTimer!

And then make a timer (probably a .strict one that is not subject to coalescing, app nap, etc., with awareness of the power/battery/etc. implications that entails) with makeTimerSource(flags:queue:):

let queue = DispatchQueue(label: "com.domain.app.timer", qos: .userInteractive)
timer = DispatchSource.makeTimerSource(flags: .strict, queue: queue)
timer.scheduleRepeating(deadline: .now(), interval: 0.0001, leeway: .nanoseconds(0))
timer.setEventHandler { 
    // do something
}
timer.resume()

Note, you should gracefully handle situations where the timer cannot handle the precision you are looking for. As the documentation says:

Note that some latency is to be expected for all timers, even when a leeway value of zero is specified.



来源:https://stackoverflow.com/questions/43746336/high-precision-timer-in-swift

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