方法1——CFAbsoluteTime
CFAbsoluteTime startTime = CFAbsoluteTimeGetCurrent();
//这部分为需要统计时间的代码
CFAbsoluteTime endTime = (CFAbsoluteTimeGetCurrent() - startTime);
NSLog(@"方法耗时: %f ms", endTime * 1000.0);
方法2——NSDate
double start = [[NSDate date] timeIntervalSince1970]*1000;
//这部分为需要统计时间的代码
double end = [[NSDate date] timeIntervalSince1970]*1000;
NSLog(@"方法耗时: %f ms ", (end-start));
方法3——mach_absolute_time()
#include <mach/mach_time.h>
// timebase, 即系统时钟每滴答一次的转化系数
mach_timebase_info_data_t timebase;
mach_timebase_info(&timebase);
// mach_absolute_time获取从开机到现在的系统时钟滴答数
uint64_t start = mach_absolute_time();
//这部分为需要统计时间的代码
uint64_t end = mach_absolute_time();
uint64_t cost = (end - start) * timebase.numer / timebase.denom;
// timebase.number / timebase.denom
// 含义为转化系数 即 系统时钟每滴答一次 相当于多少 纳秒
// 由此计算总共经过的纳秒数 = 滴答数 * 每滴答一次所占用的纳秒数
NSLog(@"方法耗时: %f ms",(CGFloat)cost / NSEC_PER_SEC * 1000.0);
需要导入头文件:
#import <mach/mach_time.h>
作者:WonderChang
链接:https://www.jianshu.com/p/ffc2f7e31279
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。