OSX: programmatically get uptime?

2020-02-10 04:41发布

Something similar to linux

cat /proc/uptime

which returns the uptime in seconds, and preferably not parsing uptime(1).

标签: macos uptime
7条回答
何必那么认真
2楼-- · 2020-02-10 04:58

There is a function UpTime declared in DriverServices.h. I believe this is equivalent to another function mach_absolute_time. Both seem to be undocumented.

查看更多
冷血范
3楼-- · 2020-02-10 04:59

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.

查看更多
别忘想泡老子
4楼-- · 2020-02-10 05:06

The Uptime article on Wikipedia has an interesting lead:

Using sysctl

There is also a method of using sysctl to call the system's last boot time: $ sysctl kern.boottime kern.boottime: { sec = 1271934886, usec = 667779 } Thu Apr 22 12:14:46 2010

Which references sysctl(8), which references sysctl(3).

查看更多
女痞
5楼-- · 2020-02-10 05:11

A simple Lua script to do exactly what you ask for:

local now=tonumber(io.popen("date +%s"):read())
local boottime=tonumber(io.popen("sysctl -n kern.boottime"):read():match("sec = (%d+)"))
local uptime=now-boottime
查看更多
Root(大扎)
6楼-- · 2020-02-10 05:17

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

#include <time.h>
#include <errno.h>
#include <sys/sysctl.h>

double uptime()
{
    struct timeval boottime;
    size_t len = sizeof(boottime);
    int mib[2] = { CTL_KERN, KERN_BOOTTIME };
    if( sysctl(mib, 2, &boottime, &len, NULL, 0) < 0 )
    {
        return -1.0;
    }
    time_t bsec = boottime.tv_sec, csec = time(NULL);

    return difftime(csec, bsec);
}
查看更多
forever°为你锁心
7楼-- · 2020-02-10 05:18

correct way:

CFTimeInterval getSystemUptime(void)
{
    enum { NANOSECONDS_IN_SEC = 1000 * 1000 * 1000 };
    static double multiply = 0;
    if (multiply == 0)
    {
        mach_timebase_info_data_t s_timebase_info;
        kern_return_t result = mach_timebase_info(&s_timebase_info);
        assert(result == noErr);
        // multiply to get value in the nano seconds
        multiply = (double)s_timebase_info.numer / (double)s_timebase_info.denom;
        // multiply to get value in the seconds
        multiply /= NANOSECONDS_IN_SEC;
    }
    return mach_absolute_time() * multiply;
}

also you could use CACurrentMediaTime() from QuartzCore.framework (which has same code probably) - Available since OS X v10.5 and iOS 2.0

查看更多
登录 后发表回答