使用dispatch_benchmark函數進行基準測試,benchmark函數
dispatch_benchmark函數是libdispatch (Grand Central Dispatch) 的一部分,這個方法並沒有被公開聲明,所以必須要自己聲明。
簡介
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.
函數原型
extern uint64_t dispatch_benchmark(size_t count, void (^block)(void))
執行個體代碼
#import <Foundation/Foundation.h> // 聲明GCD中dispatch_benchmark函數原型extern uint64_t dispatch_benchmark(size_t count, void (^block)(void)); void test1(void);void test2(void); int main(int argc, const char * argv[]) { @autoreleasepool { test1(); test2(); } return 0;} void test1(void) { // 執行次數 size_t count = 1000; // 調用dispatch_benchmark函數,傳入執行次數和待測試的代碼塊 NSUInteger length = 1000000; uint64_t time = dispatch_benchmark(count, ^{ @autoreleasepool { NSMutableArray *mutableArray = [NSMutableArray array]; for (NSUInteger i = 0; i < length; i++) { [mutableArray addObject:@(i)]; } } }); NSLog(@"[[NSMutableArray array] addObject:] Avg. Runtime: %llu ns", time);} void test2(void) { // 執行次數 size_t count = 1000; NSUInteger length = 1000000; // 調用dispatch_benchmark函數,傳入執行次數和待測試的代碼塊 uint64_t time = dispatch_benchmark(count, ^{ @autoreleasepool { NSMutableArray *mutableArray = [NSMutableArray arrayWithCapacity:length]; for (NSUInteger i = 0; i < length; i++) { [mutableArray addObject:@(i)]; } } }); NSLog(@"[[NSMutableArray arrayWithCapacity:] addObject:] Avg. Runtime: %llu ns", time);}