gpt4 book ai didi

swift - Apple Watch 上的 CoreMotion OperationQueue 问题

转载 作者:行者123 更新时间:2023-11-28 07:53:05 25 4
gpt4 key购买 nike

设备:iPhone 8、Apple Watch Series 3

我目前正在开发一个手机应用 + watch 扩展,它使用标准 API 和相关的 OperationQueues 从所有 CoreMotion 传感器流式传输 CoreMotion 数据。

我需要能够并行传输所有 CoreMotion 传感器,将样本写入 csvs,然后导出它们。将样本存储在数组中的内存中会按预期导致内存压力问题,所以现在我将每个样本在收到时直接写入文件 - 因此对于 X=# 的流式传感器,我也有 X 个文件被写入,也在相关的操作队列。

我的流式处理代码如下所示(例如,用于加速):

public func start(mm: CMMotionManager, fileQueue: OperationQueue, myOutputURL: URL) {
if mm.isAccelerometerAvailable && !mm.isAccelerometerActive {
mm.startAccelerometerUpdates(to: sampleQueue, withHandler: { (sample: CMLogItem?, error: Error?) in
if let error = error as NSError? {
print("There was a sampling error --- \(error.localizedDescription)")
} else {
if let accelerometerData = sample as? CMAccelerometerData {
let now = Date().timeIntervalSince1970
let sampleComponents: [Double] = [
now,
accelerometerData.timestamp,
accelerometerData.acceleration.x,
accelerometerData.acceleration.y,
accelerometerData.acceleration.z
]
let row = sampleComponents.map({ String(format: "%.5f", $0) })
let sampleString = row.joined(separator: ",") + "\n"
if FileManager.default.fileExists(atPath: myOutputURL.path)
let writeOperation = BlockOperation(block: {
do {
if let utf8Sample = sampleString.data(using: .utf8) {
let fileHandle = try FileHandle(forWritingTo: myOutputURL)
fileHandle.seekToEndOfFile()
fileHandle.write(utf8Sample)
fileHandle.closeFile()
}
} catch let error as NSError {
print("There was an error while writing to file --- \(error.localizedDescription)")
}
})
if let lastOperation = fileQueue.operations.last {
writeOperation.addDependency(lastOperation)
}
fileQueue.addOperation(writeOperation)
print("Num OPs in Sample Queue: \(sampleQueue.operations.count)")
print("Num OPs in I/O Queue: \(fileQueue.operations.count)")
}
}
})
}
}

这很好用……在电话上。采样操作队列在任何给定时间很少有超过 100 个总操作,并且文件队列最多 5 个 - 即使流式传输超过一个小时。然而,我在我的 watchkit 扩展中使用完全相同的代码来传输加速和运动数据,并且发生了一些奇怪的事情。传感器数据的样本队列无限增加。换句话说,就好像来自 CoreMotion 采样的操作永远不会从采样队列中取出。

旁注:除了依赖链,队列还配置了:

    sampleQueue.maxConcurrentOperationCount = 1
fileQueue.maxConcurrentOperationCount = 1

希望按顺序接收和编写样本。

这种无限增加导致内存分配在大约 15 分钟的流式传输后接近 80MB,我根据经验发现这是我的 watch 操作系统因压力过大而终止扩展时的近似上限。当每个样本进入时,我已经记录了样本队列中的操作数,当它接近 80MB 标记时,队列中大约有 60-80k 个操作,而在 I/O 队列中,这个数字类似于电话的那个。我不明白为什么,因为更直观的是,瓶颈将存在于磁盘 I/O 队列中,而不是样本队列中,尤其是随着文件大小和样本数量的增加。

我很好奇其他人是否遇到过这样的问题以及他们是如何克服它的,因为这似乎是从 Apple 设备存储和导出传感器数据的一个相当标准的问题。

具体来说,我很好奇其他人如何设法在这些设备上长时间传输和存储传感器数据以供日后分析,以及您是否觉得我做的事情不正确。非常感谢!

最佳答案

我认为这样做的关键是尽可能少地对 watch 本身进行处理。

这并没有直接解决问题,但我所做的是将数据从 Watch 流式传输到 iPhone,并在 iPhone 上完成对 CSV 的处理。这避免了让 watch 做任何繁重的工作(这对于旧 watch 来说更为重要)。

另外,你的 updateInterval 是多少?

关于swift - Apple Watch 上的 CoreMotion OperationQueue 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49181216/

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