gpt4 book ai didi

swift - 如何在 0.3 秒后执行给定次数的 Action ?

转载 作者:搜寻专家 更新时间:2023-10-30 21:58:49 25 4
gpt4 key购买 nike

let expecation = expectationWithDescription("do tasks")
for i in 0...40 {

let afterTiming = 0.3 * Double(i)
let startTime = CFAbsoluteTimeGetCurrent()

let delayTime = dispatch_time(DISPATCH_TIME_NOW, Int64(afterTiming * Double(NSEC_PER_SEC)))

dispatch_after(delayTime, dispatch_get_main_queue()) {
let timeElapsed = CFAbsoluteTimeGetCurrent() - startTime
print("\(afterTiming) - \(timeElapsed) : \(i)")
}
}

waitForExpectationWithTimeout(14)

在 30 执行后将近一秒,控制台开始表现怪异,同时显示两条和两条打印线

9.0 - 9.88806998729706 : 30
9.3 - 9.88832598924637 : 31

XCTest 是否有任何方法可以更接近于“在正确的时间”实际执行请求?就像得到应该在 9 秒后完成的请求在 9.88 秒后没有完成..

最佳答案

不确定您是否准备使用分派(dispatch),但 NSTimer 在我的测试中表现得更加准确。下面是一些示例代码,用于运行一个 Action numOfTimes 次

var iterationNumber = 0
var startTime = CFAbsoluteTimeGetCurrent()
let numOfTimes = 30

// Start a repeating timer that calls 'action' every 0.3 seconds
var timer = NSTimer.scheduledTimerWithTimeInterval(0.3, target: self, selector: #selector(ViewController.action), userInfo: nil, repeats: true)

func action() {
// Print relevant information
let timeElapsed = CFAbsoluteTimeGetCurrent() - startTime
print("\(Double(iterationNumber+1) * 0.3) - \(timeElapsed) : \(CFAbsoluteTimeGetCurrent())")

// Increment iteration number and check if we've hit the limit
iterationNumber += 1
if iterationNumber > numOfTimes {
timer.invalidate()
}
}

程序的一些输出:

7.8 - 7.80285203456879 : 25
8.1 - 8.10285001993179 : 26
8.4 - 8.40283703804016 : 27
8.7 - 8.70284104347229 : 28
9.0 - 9.00275802612305 : 29
9.3 - 9.3028250336647 : 30

它保持在预期时间的几毫秒内(我假设这是调用 CFAbsoluteTimeGetCurrent 所需的时间)并且不会漂移或将它们聚集在一起。

这种方法的一个缺点是它不会像在您的代码中那样预先安排每个操作,尽管我不确定这对您是否重要。

关于swift - 如何在 0.3 秒后执行给定次数的 Action ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36693913/

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