前言
在日常开发过程中,我们经常会遇到这样的疑问:
这段代码相对效率是多少?方法A与方法B哪个更快?
打时间戳
逻辑很简单:代码运行前记录一次时间,运行后记录一次,然后比较时间差即可。
1 | CFTimeInterval startTime = CACurrentMediaTime(); |
diapatch_benchmark
dispatch_benchmark 是 libdispatch (Grand Central Dispatch) 的一部分。但这个方法并没有被公开声明,所以你必须要自己声明:
1 | extern uint64_t dispatch_benchmark(size_t count, void (^block)(void)); |
因为没有公开的函数定义, dispatch_benchmark 在 Xcode 中也没有公开的文档。但幸运的是有 man 页面
dispatch_benchmark(3)
The dispatch_benchmark function executes the given block multiple times according to the count variable and then returns the average number of nanoseconds per execution. This function is for debugging and performance analysis work. For the best results, pass a high count value to dispatch_benchmark.
Please look for inflection points with various data sets and keep the following facts in mind:
- Code bound by computational bandwidth may be inferred by proportional changes in performance as concurrency is increased.
- Code bound by memory bandwidth may be inferred by negligible changes in performance as concurrency is increased.
- Code bound by critical sections may be inferred by retrograde changes in performance as concurrency is increased.
- Intentional: locks, mutexes, and condition variables.
- Accidental: unrelated and frequently modified data on the same cache-line.
dispatch_benchmark是一个根据传入的count参数多次执行给定block然后返回平均执行时间(纳秒)的方法。这个方法用于调试和测试分析代码性能。为了获取跟好的效果,传入的一个较大的count值
使用Sample
对于iOS中NSMutableArray,它对首尾插入/删除有较高的效率,近乎常数。
下面我们对比下,首尾删除与在中间删除有多少差距。
1 | //测试函数 |
1 | //调用 |
上面代码可以看出,初始化了一个数量为200000的可变数组,分别在中间、首尾移除数组元素,执行100次。
执行结果
1 | Remove Array At Middle Avg. Runtime: 21851 ms |