swift - 快速计时器滞后
问题描述
我知道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
}
}
我希望在 和 之间得到大致相同的结果count
,duration
但我看到了这样奇怪的事情:
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 上测试。我在这里做错了吗?
解决方案
没错,但是您错过了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 电池寿命等都是不利的。
推荐阅读
- java - 如何将 Springboot api 连接到 SAP(不是 SAP-Hana),是否需要添加任何依赖项或只是一个简单的代码建议?
- java-8 - 应用程序无法使用类路径启动:
- maven - IntelliJ 不使用本地 Maven 下载的工件
- mysql - 在触发器中的更新语句中为变量赋值
- python-2.7 - python 字典具有多个键的属性。如何在其中一个属性中找到最小值并返回键?
- r - 按数据集中的外观对交叉表的列和行进行排序
- c# - 是否可以按顺序启动后台工作人员?
- django - Django“python-social-auth”:github的HTTP 403客户端错误
- node.js - Mongoose - 获取匹配字段的数量
- winapi - 我需要使用 Microsoft Paint 打开图像