版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/jiaxin_1105/article/details/82223017
背景:
在App的开发中,会遇到一些要计算时间差的问题,比如:在友盟统计的列子里面,要统计一个页面从创建到销毁的时间或者统计用户在一个页面停留的时间。例如:我们数据缓存的情况下,要求在一个小时后从新刷新等情况。我们都要计算时间的间隔。方法有:时间戳 、CFAbsoluteTimeGetCurrent()等。
框架层:
NSDate 属于Foundation框架
CFAbsoluteTimeGetCurrent()属于CoreFoundation框架
CACurrentMediaTime()属于QuartzCore框架
区别:
NSDate
或CFAbsoluteTimeGetCurrent() 返回网络时间同步的时钟时间
。
mach_absolute_time()
和CACurrentMediaTime()
是系统时间,是基于内建时钟的,能够更精确更原子化地测量,并且不会因为外部时间变化而变化(例如时区变化、夏时制、秒突变等),但它和系统的uptime有关,系统重启后CACurrentMediaTime()会被重置。
应用场景:
NSDate、
CFAbsoluteTimeGetCurrent
()常用于日常时间、时间戳的表示,与服务器之间的数据交互,其中 CFAbsoluteTimeGetCurrent() 相当于[[NSDate data] timeIntervalSinceReferenceDate];
CACurrentMediaTime() 常用于测试代码的效率;
应用:
CFAbsoluteTime start = CFAbsoluteTimeGetCurrent(); NSMutableArray * arr = @[@1,@2,@3,@4,@5].mutableCopy; for (NSNumber *obj in arr) { NSLog(@"%@",obj); } CFAbsoluteTime end = CFAbsoluteTimeGetCurrent(); NSLog(@"for in cost: %0.3f",end - start); CFAbsoluteTime startTime = CFAbsoluteTimeGetCurrent(); for (int i = 0; i < arr.count; i ++) { NSLog(@"%@",arr[i]); } CFAbsoluteTime endTime = CFAbsoluteTimeGetCurrent(); NSLog(@"for cost: %0.3f",endTime - startTime);
相关文章