search

Home  >  Q&A  >  body text

objective-c - iOS: 零误差或极小误差的定时执行或延迟执行?

问题如下:

节奏类游戏需要执行很多的跟音乐节拍相关的操作,并且为了保证节奏感,需要让操作跟节拍的关系十分紧密。对两者间隔要求不能超过0.02秒或更低。

目前使用了 GCD 中的 asyncAfter(deadline:)方法,不过误差总是要大于0.05秒,并且还无法保证误差会不会传递下去。请问有更好的方式来解决误差吗?

var time = Date().timeIntervalSince1970
let dq = DispatchQueue(label: "queue", qos: .userInitiated, attributes: [.concurrent, .initiallyInactive])
            dq.async {
                self.audioPlayer.play()
                time = Date().timeIntervalSince1970
            }
            dq.asyncAfter(deadline: .now() + 0.43, execute: {
                let res = Date().timeIntervalSince1970
                print(" 误差: \(res - time)")
                
            })

以下是多次运行控制台打印结果(该数字指的是实际间隔,与期望间隔的0.43相差甚远,且不稳定):

阿神阿神2772 days ago536

reply all(3)I'll reply

  • PHP中文网

    PHP中文网2017-04-18 09:58:48

    http://blog.lessfun.com/blog/...

    reply
    0
  • 巴扎黑

    巴扎黑2017-04-18 09:58:48

    CADisplayLink?

    reply
    0
  • 怪我咯

    怪我咯2017-04-18 09:58:48

    Mention an engineering rather than a technical idea.

    When the program starts, it first runs the test for the average delay time, and then still uses the standard time for timing, but uses the difference between the standard time and the average delay time to delay execution.

    reply
    0
  • Cancelreply