Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

high precision timer in 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.

like image 811
Alexander Avatar asked May 02 '17 20:05

Alexander


1 Answers

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.

like image 174
Rob Avatar answered Nov 19 '22 10:11

Rob