整理了两种iOS中获取一个方法执行时间的方法,不多说,直接上代码
方法一
需要导入头文件 #import <mach/mach_time.h>
CGFloat duration_time_block (void (^block) ()) {
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;
int64_t nanos = elapsed * info.numer / info.denom;
return (CGFloat)nanos / NSEC_PER_SEC;
}
方法二
CGFloat clock_time_block (void (^block) ()){
time_t time1 = clock();
block();
time_t time2 = clock();
return ((CGFloat)(time2 - time1)) / CLOCKS_PER_SEC;
}