ProcessInfo systemUptime

Hi community!
I hope you can help me on that or at least you can clarify my doubt.


In my App for Mac (macOS, Swift, Xcode .. everything is at the latest official version) I need to get the System Uptime and for this reason I use this API (ProcessInfo/processInfo/systemUptime):

https://developer.apple.com/documentation/foundation/processinfo/1414553-systemuptime


This is my fragment of code:


let systemUptime = ProcessInfo.processInfo.systemUptime


Executing it right now I get the following values (in seconds): 32967.776459317 which is about 9 hours, while getting the System Uptime from the Terminal I get (correctly): 1 day, 12:27


My questions is obviusly, how can I get the correct System Uptime using Swift?


Thanks in advance for your time and help!

Replies

[There’s nothing Swift specific here so I’ve moved the thread over to Core OS > Kernel, which is probably the best match.]

The problem here is one of definition. By my count there are three separate concepts entangled here:

  • How long has the CPU been running? (A)

  • When did the computer boot? (B)

  • How much time has expired between then and now? (C)

Which one of these do you want?

ps I believe that

systemUptime
is returning A. As far as I can tell the
uptime
command-line tool is basing its calculation on B. Finally, note that B and C aren’t necessarily in sync because the system clock might have changed.

Share and Enjoy

Quinn “The Eskimo!”
Apple Developer Relations, Developer Technical Support, Core OS/Hardware

let myEmail = "eskimo" + "1" + "@apple.com"

Hi Eskimo,

thanks for your feedback on that.


What I need is to have the same exact result of the terminal command "uptime". Based on what I see here, (A) which is the output of the API "systemUptime" is giving me back the "awake" time. I think this has clarified my doubt 🙂


Many thanks and have a good day!

Gennaro

What I need is to have the same exact result of the terminal command

uptime
.
uptime
is part of Darwin, so you can just look at the source code. Specifically, check out the
pr_header
routine in w.c. It uses the
CTL_KERN
>
KERN_BOOTTIME
selector to
sysctl
to get the kernel boot time and then does calendar maths from there.

IMPORTANT Personally I wouldn’t replicate this calendar maths because it’s hopelessly naïve. Rather, I’d use

NSCalendar
to calculate this difference, or just go straight to
NSDateComponentsFormatter
to render the difference.

Share and Enjoy

Quinn “The Eskimo!”
Apple Developer Relations, Developer Technical Support, Core OS/Hardware

let myEmail = "eskimo" + "1" + "@apple.com"