Thursday 13 September 2012

Mac OS X -- Get Uptime, Sleep and Wake Times

As I argued before, the single most important feature of the MacBook Air is its instant-on ability. This makes it very easy and non-obtrusive to just pull it off my bag, do something very quickly and then push it back.

And yesterday, I did just that. While I was sipping my coffee at the office, I wanted to quickly check some code I have written the previous evening. So I turned the MacBook on, in a few seconds had Xcode  up and running and a few minutes later I finished doing the checks I wanted to. Then I returned to the coffee and a chat with my colleagues, leaving the Air on my desk.

A few hours later, I put the computer into my backpack not even realising it is still turned on (as it turned out, it was in sleep mode). I figured out what happened just this morning when I was greeted by a warning message that my external drive wasn't properly ejected.

Ooops.

Obviously, putting a sleeping laptop in a case or a bag is not a big deal and many people are even doing this regularly, shutting down their machines only occasionally. Still, as this is not the normal way I handle my laptops, I decided I wanted to know more.

Obviously, the first thing I needed to check was how long the system was running just to make sure it was indeed on.
You do this with the good old uptime command:


'A-ha', I said to myself, so the computer was indeed running for a day (most of the time sitting in the shock-proof department of my Samsonite bag).

The next big question I had was if the computer was sleeping and for how long.
To find out the time the computer entered in sleep mode, in MacOS X (and any UNIX-like system) you use the sysctl command with the following syntax:
sysctl -a | grep sleeptime
sysctl is a powerful UNIX utility to retrieve and modify the kernel state. The sysctl -a output is more than 800 lines long (although your mileage will vary) and that's why I used grep to only output the time the kernel fell asleep:


So the computer was sleeping since 12:25 p.m. on the previous day, which is a good news. The last important piece of the puzzle was when the computer woke up. I wanted to know if something didn't wake the laptop while in the bag.
Again, sysctl -a does the job here. Instead of grep-ing for sleeptime, however, this time we grep for, wait for it, waketime.



So the MacBook effectively was sleeping for 21 hours, most of that time being zipped in the backpack.
Great.

All I had to do next was to (just in case) run a disk check with DiskUtility to ensure my volumes are in a good state.