在Swift中使用DispatchQueue时的时间差异 [英] Discrepancies in time when using DispatchQueue in Swift
问题描述
我有一个必须每半秒执行一次的代码,并且我正在使用Xcode游乐场.我使用了最佳答案,并得到了类似的代码这个:
I've got a code which must be executed every half a second and I'm using the Xcode playground. I used this top answer and got a code like this:
for (index, item) in array.enumerated() {
DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(index), execute: {
print("\(index) - \(df.string(from: Date()))"
//play sound every second
})
}
此代码每秒执行一次(我知道我必须将其除以2以得到半秒,但想查看结果).我用 DateFormatter
来计算时间,因为我无法弄清楚为什么声音不能均匀播放.
This code is executed every second (I know that I have to divide it by 2 to get half a second but wanted to see the results). I used the DateFormatter
to figure out times because I couldn't figure out why sounds are not played evenly.
let df = DateFormatter()
df.dateFormat = "ss.SSSS"
结果是并非每隔1秒就触发一次.
The result is that it is not triggered exactly every 1 second.
0 - 17.4800
1 - 18.5770 // even though it's not called exactly after 1s it's acceptable
2 - 19.6750
3 - 20.7770
4 - 21.8780
5 - 22.9760
6 - 24.0710
7 - 25.1690
8 - 26.2720
9 - 27.3640
10 - 28.4760
11 - 28.7580 //0.3s of difference
12 - 30.4800
13 - 30.5060 // 0.1s of difference
14 - 32.4800
15 - 32.5030 // less than 0.1s of difference
推荐答案
在这里您异步执行 Print
语句,因此半秒钟(或一秒钟)后就不会获取打印数据.您可以同步执行它,然后获得打印数据1秒间隔.要了解有关调度队列的更多信息,请遵循此链接.如果您有任何问题,请告诉我.
Here you execute your Print
statement asynchronous so you do not get your printed data after half a second(or one second).If you execute it synchronously then you get your printed data 1 second interval.To know more about dispatch queue follow this link.Let me know if you have any problem.
这篇关于在Swift中使用DispatchQueue时的时间差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!