变更记录

序号 录入时间 录入人 备注
1 2016-02-19 Alfred Jiang -

方案名称

时间 - 使用 Benchmarking 精确测量的代码运行时间

关键字

Benchmarking \ 测量 \ 代码运行时间

需求场景

  1. 需要对函数进行运行时间测量时
  2. 需要比较两个函数运行时间时

参考链接

  1. NSHipster - Benchmarking

详细内容

1. 使用 CFAbsoluteTimeGetCurrent

和 NSDate 或 CFAbsoluteTimeGetCurrent() 偏移量不同的是,mach_absolute_time() 和 CACurrentMediaTime() 是基于内建时钟的,能够更精确更原子化地测量,并且不会因为外部时间变化而变化(例如时区变化、夏时制、秒突变等)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
CFTimeInterval startTime = CACurrentMediaTime();
{
static size_t const count = 1000;
static size_t const iterations = 10000;

id object = @"🐷";

for (size_t i = 0; i < iterations; i++) {
@autoreleasepool {
NSMutableArray *mutableArray = [NSMutableArray array];
for (size_t j = 0; j < count; j++) {
[mutableArray addObject:object];
}
}
}
}
CFTimeInterval endTime = CACurrentMediaTime();
NSLog(@"Total Runtime: %g s", endTime - startTime);
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
2
3
4
5
6
7
8
9
uint64_t t = dispatch_benchmark(iterations, ^{
@autoreleasepool {
NSMutableArray *mutableArray = [NSMutableArray array];
for (size_t i = 0; i < count; i++) {
[mutableArray addObject:object];
}
}
});
NSLog(@"[[NSMutableArray array] addObject:] Avg. Runtime: %llu ns", t);

效果图

(无)

备注

(无)