Well, that depends. CLOCK_MONOTONIC_RAW does avoid NTP slewing, but NTP doesn't just adjust the time scale to adjust for offsets - it also attempts to correct for frequency error in your system clock itself. If you use CLOCK_MONOTONIC_RAW, you don't get that correction; you get something that on desktop hardware can easily be tens of ppm off from actual time. Of course, your MONOTONIC_RAW clock is still subject to the vagaries of physics; as temperature or system load changes, depending on the quality of your time source, you might get significant changes in the rate of CLOCK_MONOTONIC_RAW as well (which NTP will correct for in CLOCK_MONOTONIC, given enough time to adjust).
Right? I mean maybe he microbenchmarked it and looping is faster because no div or mod, but intuitively this seems like it would be better. If the loops are a result of benchmarking, it should probably be called out in comments.
I sometimes deliberately write really slow, stupid C code when dealing with time or other things that are both extremely important and (if I'm honest with myself) unlikely to be tested exhaustively.
Apple has really awesome developers who don't need to do stuff like this, and that's probably why iPhone alarms fail to go off every other leap year and reliably sound at 2 AM on January 32nd of years ending in '3'. Time-related code is like rolling your own encryption, in a sense. It's a trap for amateurs and pros alike.
I don't really understand how ts_remaining.tv_nsec > 1000000000
could ever be true. I thought we had a-b, with a<1000000000 and b>=0.
For the negative check, the loop should only be able to run once, so could be changed to an 'if' for clarity. Regarding the timing, branching is probably faster.
It is my understanding that the c percent operator can produce a negative number by the way, so your code wouldn't work.
The correct call is to clock_gettime(CLOCK_MONOTONIC_RAW...