Swift中的高精度计时器

编程入门 行业动态 更新时间:2024-10-10 17:33:17
本文介绍了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!

,然后使用.strict计时器,该计时器不受合并,应用程序午睡等影响,并且意识到其中涉及的电源/电池/等方面的隐患)://developer.apple/reference/dispatch/dispatchsource/2300106-maketimersource"rel =" noreferrer> makeTimerSource(flags:queue:) :

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中的高精度计时器

本文发布于:2023-11-06 08:40:56,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1563207.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:计时器   Swift

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!