Hacker News new | past | comments | ask | show | jobs | submit login

    while (ts_remaining.tv_nsec > 1000000000) {
        ts_remaining.tv_sec++;
        ts_remaining.tv_nsec -= 1000000000;
    }
should be

    int secs_in_nsec = ts_remaining.tv_nsec / 1000000000;
    ts_remaining.tv_sec += secs_in_nsec;
    ts_remaining.tv_nsec %= 1000000000;
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.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: