標籤:
第一種:(最簡單的NSDate)
NSDate* tmpStartData = [NSDate date];//You code here...double deltaTime = [[NSDate date] timeIntervalSinceDate:tmpStartData];NSLog(@"cost time = %f", deltaTime);
第二種:(將運行代碼放入下面的Block中,返回時間)
#import <mach/mach_time.h> // for mach_absolute_time() and friends CGFloat BNRTimeBlock (void (^block)(void)) { mach_timebase_info_data_t info; if (mach_timebase_info(&info) != KERN_SUCCESS) return -1.0; uint64_t start = mach_absolute_time (); block (); uint64_t end = mach_absolute_time (); uint64_t elapsed = end - start; uint64_t nanos = elapsed * info.numer / info.denom; return (CGFloat)nanos / NSEC_PER_SEC; }
第三種:
/** * 計算指令碼時間 * @param $last 最後一次的運行clock * @param $key 標識 * @return 當前clock */double t(double last, char* key){ clock_t now = clock(); printf("time:%fs \t key:%s \n", (last != 0) ? (double)(now - last) / CLOCKS_PER_SEC : 0, key); return now;}double t1 = t(0, "");//do somethingt(t1, "end");
使用Objective-C 計算代碼已耗用時間