> For the complete documentation index, see [llms.txt](https://awesome-tips.gitbook.io/ios/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://awesome-tips.gitbook.io/ios/qi-ta/content-14.md).

# 15. iOS中的mach\_continuous\_time()方法

**作者**: [高老师很忙](https://weibo.com/517082456)

`mach_absolute_time()` 这个函数大家应该比较了解：返回的是CPU已经运行的时钟周期数，可以转化为秒数，这个是不会受本地时间影响的，不过当手机重启会重新开始计数，锁屏休眠后会暂停计数。今天看文档惊喜的发现了 `iOS10` 之后提供了 `mach_continuous_time()` 方法：

![](https://3602781484-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LUYeWAm5IWBtrAOZ2Bb%2F-LUYjcutxneQXizIQfB1%2F-LUYjhQpSSOgyfd2yFUr%2F1.jpg?generation=1545714211632215\&alt=media)

注释写的是：

> like mach\_absolute\_time, but advances during sleep

突然感觉好惊喜，查看了一下源码：

![](https://3602781484-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LUYeWAm5IWBtrAOZ2Bb%2F-LUYjcutxneQXizIQfB1%2F-LUYjhQrqWJqnongd8wM%2F2.jpg?generation=1545714211015670\&alt=media)

通过休眠测试（使用 `iPhone8+` , `iOS11` ,删除所有 `APP`, 关掉网络和蓝牙等，先运行 `demo` 获取一个时间，锁屏过了几个小时，再次获取时间)，结果果然可喜：

![](https://3602781484-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LUYeWAm5IWBtrAOZ2Bb%2F-LUYjcutxneQXizIQfB1%2F-LUYjhQt7QWrOQytJvY7%2F3.jpg?generation=1545714211568709\&alt=media)

不过重启后仍然会重置。顺便再介绍一下 `mach_approximate_time()`，是获取一个大约时间，暂时没有用过，可以简单看下源码：

![](https://3602781484-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LUYeWAm5IWBtrAOZ2Bb%2F-LUYjcutxneQXizIQfB1%2F-LUYjhQvz1rZwYl5lXqm%2F4.jpg?generation=1545714208157747\&alt=media)

比较好理解。希望能帮助到大家！
