swift - Swift OperationQueue 开始下一个操作的时间
问题描述
我有一组异步操作并具有相互依赖关系的任务。现在这一切都是用自定义代码管理的,我想改用 OperationQueue。但是,时序性能非常关键。
对于当前的实现,当一个任务完成时,它会立即调用所需的代码来启动下一个任务。所以所涉及的时间只是调用一个函数。现有任务相当少,有些是异步的,有些是单个函数调用。
从一个操作完成到下一个操作开始所涉及的时间是多少?
解决方案
当你有这样的问题时,你可能只想测量它。路标和兴趣点(使用 Instruments 来“分析”应用程序)是衡量性能的好方法。因此:
import os.signpost
let pointsOfInterest = OSLog(subsystem: "Operations", category: .pointsOfInterest)
和:
let queue = OperationQueue()
queue.maxConcurrentOperationCount = 1
var id = OSSignpostID(log: pointsOfInterest)
queue.addOperation {
os_signpost(.begin, log: pointsOfInterest, name: "Operation", signpostID: id)
}
for _ in 0 ..< 100 {
queue.addOperation {
os_signpost(.end, log: pointsOfInterest, name: "Operation", signpostID: id)
id = OSSignpostID(log: pointsOfInterest)
os_signpost(.begin, log: pointsOfInterest, name: "Operation", signpostID: id)
}
}
queue.addOperation {
os_signpost(.end, log: pointsOfInterest, name: "Operation", signpostID: id)
}
我个人确保在进行这些测试之前让应用程序进入静止状态,通常只需将例程延迟几秒钟,这样它就可以减少标准应用程序启动开销,否则可能会改变结果。我还会对我的基准测试进行多次迭代,以获取更具代表性的结果集。
使用 Instruments 的 Points of Interest 工具对其进行分析可以获取这组结果并为我们总结它们。例如,在我的 MacBook Pro 上运行的 iOS 模拟器上,它报告:
最小值:31.69 µs
平均:74.70 µs
标准差:24.05 µs
最大值:154.10 µs
在我的 iPhone XS Max 上:
最小值:44.92 µs
平均值:125.78 µs
标准差:43.61 µs
最大值:446.88 µs
您的里程可能会有所不同,但它以粗略的数量级说明了它需要的那种开销。最重要的是,对于大多数用例来说,开销可以忽略不计。
如果您有其他想要测试的场景,请随意。希望这说明了如何使用 Instruments 中的 Points of Interest 工具来衡量性能。有关更多信息,请参阅仪器入门。
推荐阅读
- ios - 尝试通过 VTDecompressionSessionDecodeFrame 传递和读取 UnsafeMutableRawPointer 时的 EXC_BAD_ACCESS
- matlab - 你如何使用while循环计算算术级数的总和?
- powerbi - 如何计算 Power BI 中的周期时间?
- sql - Msg 116, Level 16, State 1, Line 2 当子查询没有用 EXISTS 引入时,选择列表中只能指定一个表达式
- ruby-on-rails - Ruby Heroku Buildpack 因 Dokku 失败
- c++ - 我尝试将 SDL2 添加到我的项目中,但出了点问题
- git - 你可以在合并后运行 git 代码吗,就像在 dump-autoload 后使用 composer 一样?
- javascript - 如何使用 Vue.js 提取 gmail 数据
- java - PluginManager 中的 java.lang.NullPointerException
- wordpress - Woocommerce 如何按“最后修改”日期对产品进行排序?