Discrepancies in time when using DispatchQueue in Swift

房东的猫 提交于 2019-12-24 21:01:09

问题


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
            })
        }

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"

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

回答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.



来源:https://stackoverflow.com/questions/49347450/discrepancies-in-time-when-using-dispatchqueue-in-swift

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