时间 - 使用 Benchmarking 精确测量的代码运行时间
变更记录
序号 | 录入时间 | 录入人 | 备注 |
---|---|---|---|
1 | 2016-02-19 | Alfred Jiang | - |
方案名称
时间 - 使用 Benchmarking 精确测量的代码运行时间
关键字
Benchmarking \ 测量 \ 代码运行时间
需求场景
- 需要对函数进行运行时间测量时
- 需要比较两个函数运行时间时
参考链接
详细内容
1. 使用 CFAbsoluteTimeGetCurrent
和 NSDate 或 CFAbsoluteTimeGetCurrent() 偏移量不同的是,mach_absolute_time() 和 CACurrentMediaTime() 是基于内建时钟的,能够更精确更原子化地测量,并且不会因为外部时间变化而变化(例如时区变化、夏时制、秒突变等)
1 | CFTimeInterval startTime = CACurrentMediaTime(); |
2. 使用 dispatch_benchmark
dispatch_benchmark 是 libdispatch (Grand Central Dispatch) 的一部分。但严肃地说,这个方法并没有被公开声明,所以你必须要自己声明:
1 | extern uint64_t dispatch_benchmark(size_t count, void (^block)(void)); |
相比之前的秒计时,毫微秒更加精确,dispatch_benchmark 也比手动写循环的 CFAbsoluteTimeGetCurrent() 语法结构上看起来更好。
1 | uint64_t t = dispatch_benchmark(iterations, ^{ |
效果图
(无)
备注
(无)
本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 宁静至远,博雅多通!