NSDate、CFAbsoluteTimeGetCurrent 、CACurrentMediaTime 的比较

NSDate 属于 Foundation
CFAbsoluteTimeGetCurrent() 属于 CoreFoundation
CACurrentMediaTime() 属于 QuartzCore
Foundation是由CoreFoundation构建的,所以咱们可以大胆猜测CFAbsoluteTimeGetCurrent()和[[NSDate date] timeIntervalSinceReferenceDate]最终是由由同一个方法实现的。

我们追踪一下CFAbsoluteTimeGetCurrent()查看代码:

typedef double CFTimeInterval;
typedef CFTimeInterval CFAbsoluteTime;
/* absolute time is the time interval since the reference date */
/* the reference date (epoch) is 00:00:00 1 January 2001. */

CF_EXPORT
CFAbsoluteTime CFAbsoluteTimeGetCurrent(void);

从CFTimeInterval的定义和注释可以看出,CFAbsoluteTimeGetCurrent(void)返回的时间就是当前时间相对与reference date的时间。
CFTimeInterval 是对double 的重命名。
而NSTimeInterval 也是对double 的重命名。
它们之间的关系就可想而已了!
CFAbsoluteTimeGetCurrent() 其实等价于 [[NSDate new] timeIntervalSinceReferenceDate] 。

而CACurrentMediaTime()就不一样了, CACurrentMediaTime()是基于内建时钟的,能够更精确更原子化地测量,并且不会因为外部时间变化而变化(例如时区变化、夏时制、秒突变等),但它和系统的uptime有关,系统重启后CACurrentMediaTime()会被重置。

总结,CACurrentMediaTime()才是最适用于测试代码效率的。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容