Swift中的高精度计时器 [英] high precision timer in Swift
问题描述
在Swift中使用精确时钟控制外部硬件的最佳解决方案是什么?我需要编写一个循环功能,该功能可以可靠且高精度地以每秒设置的速率(几百或几千赫兹)触发.
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.
推荐答案
您可以定义GCD计时器属性(因为与NSTimer
/Timer
不同,您必须维护自己对GCD计时器的强烈引用):
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.
这篇关于Swift中的高精度计时器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!