OSX:以编程方式获得正常运行时间?
类似于 linux 的东西
cat /proc/uptime
,它返回以秒为单位的正常运行时间,并且最好不解析正常运行时间(1)。
Something similar to linux
cat /proc/uptime
which returns the uptime in seconds, and preferably not parsing uptime(1).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
老问题,我知道,但我需要做同样的事情,所以我想我应该发布我正在使用的代码,这是我从 http://cocoadev.com/wiki/FindingUptime
Old question, I know, but I needed to do the same thing so I thought I'd post the code I'm using, which I got from http://cocoadev.com/wiki/FindingUptime
Wikipedia 上的 Uptime 文章 有一个有趣的线索:
哪些引用 sysctl(8),引用 sysctl(3)。
The Uptime article on Wikipedia has an interesting lead:
Which references sysctl(8), which references sysctl(3).
如果有人尝试使用 sysctl.h 以编程方式执行此操作,并且期望返回一个类似于命令行中看到的字符串,那么我得到的返回值是一个 16 字节数组,而不是字符串:
sysctlbyname("kern.boottime", value, &size, NULL, 0);
从 [0] 索引开始以十六进制形式放入
value
的内容的示例:a9 af c6 4e 0 0 0 0 0 0 0 0 28 be 92 55
前 4 个字节(可能是前 8 个,直到 2012 年 1 月才知道)是小端字节顺序的纪元时间。
If anyone is trying to do this programmatically using
sysctl.h
and is expecting a string back like what you see in the command line, the returned value that I get is a 16 byte array, not a string:sysctlbyname("kern.boottime", value, &size, NULL, 0);
An example for what gets put into
value
in hex starting from the [0] index:a9 af c6 4e 0 0 0 0 0 0 0 0 28 be 92 55
The first 4 bytes (maybe the first 8, won't know until Jan 2012) is the epoch time in little endian byte order.
正确的方法:
您也可以使用 QuartzCore.framework 中的
CACurrentMediaTime()
(可能具有相同的代码) - 自 OS X v10.5 和 iOS 2.0 起可用correct way:
also you could use
CACurrentMediaTime()
from QuartzCore.framework (which has same code probably) - Available since OS X v10.5 and iOS 2.0为了补充 @Bleyddyn 的答案(因为已经有 11 年了,而且还在继续)...
我需要一个小实用程序来以秒为单位打印正常运行时间,所以我拿了该代码并稍微修改了一下,以便在现代 macOS 上进行编译。
您可以克隆
luckman212/uptime_s
存储库并运行./ build.sh
生成您自己的通用二进制文件,该二进制文件将简单地以秒为单位打印正常运行时间。To add to @Bleyddyn's answer (since it's 11 years and counting)...
I needed a small utility to print the uptime in seconds, so I took that code and slightly altered it to compile on modern macOS.
You can clone the
luckman212/uptime_s
repo and run./build.sh
to generate your own universal binary that will simply print the uptime in secs.DriverServices.h 中声明了一个函数
UpTime
。我相信这相当于另一个函数mach_absolute_time
。两者似乎都没有记录。There is a function
UpTime
declared in DriverServices.h. I believe this is equivalent to another functionmach_absolute_time
. Both seem to be undocumented.不幸的是,“sysctl kern.boottime”返回时间戳的秒数,而不是经过的秒数。多次调用不会增加秒数,但必须是从启动日期本身的纪元开始的秒数。
Unfortunately the "sysctl kern.boottime" returns the seconds of the timestamp, not elapsed seconds.. Multiple calls do not increase the second count, but must be seconds from epoc of the boot date itself.
一个简单的 Lua 脚本可以完全满足您的要求:
A simple Lua script to do exactly what you ask for: