方法一
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.
}];
}
區(qū)別總結(jié):
1. NSDate 與 CFAbsoluteTimeGetCurrent() 等效,返回的時鐘時間將會和網(wǎng)絡時間同步
2. CACurrentMediaTime() 是基于內(nèi)建時鐘的过咬,能夠更精確更原子化地測量塘安,并且不會因為外部時間變化而變化(例如時區(qū)變化、夏時制援奢、秒突變等)
參考文章:
Objective-C 計算代碼運行時間
iOS OC 計算代碼執(zhí)行耗時
NSDate 兼犯、CFAbsoluteTimeGetCurrent、CACurrentMediaTime 的區(qū)別