首页 > 解决方案 > 快速计时器滞后

问题描述

我知道Timer不能保证完全按照您要求的速度运行。但是,我刚刚开始了一个全新的项目:

class ViewController: NSViewController {

    var timer = Timer()
    var count: Double = 0.0
    var timeStamp: Date = Date()

override func viewDidLoad() {
    super.viewDidLoad()
    self.timer = Timer.scheduledTimer(timeInterval: 0.1,
                                      target: self,
                                      selector: #selector(self.updateCounting),
                                      userInfo: nil,
                                      repeats: true)
}

@objc func updateCounting(){
    let duration = self.timeStamp.distance(to: Date())
    print("Counting \(self.count) vs. Real life \(duration)")
    self.count = self.count + 0.1
}

}

我希望在 和 之间得到大致相同的结果countduration但我看到了这样奇怪的事情:

Counting 60.50000000000059 vs. Real life 60.64057409763336
Counting 60.60000000000059 vs. Real life 60.741435050964355
Counting 60.70000000000059 vs. Real life 70.84065008163452
Counting 60.800000000000594 vs. Real life 80.94094407558441
Counting 60.900000000000595 vs. Real life 82.99448704719543

在 Xcode 11.5、iMac 和 MacBook Pro 上测试。我在这里做错了吗?

标签: swiftmacostimernstimer

解决方案


没错,但是您错过了Mac 应用程序的能源效率指南

你的应用只是在打盹。

检查ProcessInfo& 搜索管理活动。一个例子(不好的一个)是将你的更改AppDelegate.swift为:

@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
    private var activity: NSObjectProtocol!

    func applicationDidFinishLaunching(_ aNotification: Notification) {
        let options: ProcessInfo.ActivityOptions = [.userInitiatedAllowingIdleSystemSleep]
        let reason = "No napping!"
        self.activity = ProcessInfo.processInfo.beginActivity(options: options, reason: reason)
    }

    func applicationWillTerminate(_ aNotification: Notification) {
        ProcessInfo.processInfo.endActivity(activity)
    }
}

但不要这样做,对用户、MacBook Pro 电池寿命等都是不利的。


推荐阅读