gpt4 book ai didi

ios - 在 Swift 的后台线程中执行时 usleep 的精度不佳

转载 作者:搜寻专家 更新时间:2023-11-01 07:03:31 25 4
gpt4 key购买 nike

我一直在使用“usleep”在几毫秒内停止一个线程,我已经检查过它停止的时间比预期的要多。

我确定我做错了什么,我不是 Swift 专家,但我不理解它,因为它很容易检查。例如:

DispatchQueue.global(qos: .background).async {
let timeStart: Int64 = Date().toMillis()
usleep(20 * 1000) // 20 ms
let timeEnd: Int64 = Date().toMillis()
let timeDif = timeEnd - timeStart
print("start: \(timeStart), end: \(timeEnd), dif: \(timeDif)")
}

结果:

start: 1522712546115, end: 1522712546235, dif: 120

如果我在主线程中执行同样的操作:

start: 1522712586996, end: 1522712587018, dif: 22

我认为我生成线程的方式对于停止它是错误的。我怎样才能生成适合 usleep 的线程?

谢谢

最佳答案

几个想法:

  1. usleep 的响应是Quality of Service 的一个函数的队列。例如,对五种队列类型执行三十次 20 毫秒 usleep 调用,导致以下平均值和标准偏差(以毫秒为单位):

    QoS               mean  stdev‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐   ‐‐‐‐‐ ‐‐‐‐‐background        99.14 28.06utility           74.12 23.66default           23.88  1.83userInitiated     22.09  1.87userInteractive   20.99  0.29

    The higher the quality of service, the closer to 20 ms it got, and with a lower standard deviation.

  2. If you want accurate time measurements, you should avoid using Date and/or CFAbsoluteTimeGetCurrent(). As the documentation warns us:

    Repeated calls to this function do not guarantee monotonically increasing results. The system time may decrease due to synchronization with external time references or due to an explicit user change of the clock.

    You can use a mach_time based value, such as conveniently returned by CACurrentMediaTime(), to avoid this problem. For example:

    let start = CACurrentMediaTime()
    // do something
    let elapsed = CACurrentMediaTime() - start
  3. 如果您需要更高的精度,请参阅 Apple Technical Q&A #2169 .

关于ios - 在 Swift 的后台线程中执行时 usleep 的精度不佳,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49620284/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com