方法一
NSDate* tmpStartData = [NSDate date];
//Your code here...
double deltaTime = [[NSDate date] timeIntervalSinceDate:tmpStartData];
NSLog(@"cost time = %f seconds", deltaTime);
方法二
CFAbsoluteTime start = CFAbsoluteTimeGetCurrent();
//Your code here...
CFAbsoluteTime end = CFAbsoluteTimeGetCurrent();
NSLog(@"cost time = %f seconds", end - start);
方法三
//获取的是开机到当前的时间
CFTimeInterval start = CACurrentMediaTime();
//Your code here...
CFTimeInterval end = CACurrentMediaTime();
NSLog(@"cost time = %f seconds", end - start);
方法四
添加单元测试,在单元测试方法中添加代码,按Command+U运行测试,控制台会打印出方法运行耗时
- (void)testPerformanceExample {
// This is an example of a performance test case.
[self measureBlock:^{
// Put the code you want to measure the time of here.
}];
}
区别总结:
- NSDate 与 CFAbsoluteTimeGetCurrent() 等效,返回的时钟时间将会和网络时间同步
- CACurrentMediaTime() 是基于内建时钟的,能够更精确更原子化地测量,并且不会因为外部时间变化而变化(例如时区变化、夏时制、秒突变等)
参考文章:
Objective-C 计算代码运行时间
iOS OC 计算代码执行耗时
NSDate 、CFAbsoluteTimeGetCurrent、CACurrentMediaTime 的区别
网友评论