Hacker News new | ask | show | jobs
by blue11 4637 days ago
Sorry to nitpick, but I believe the time difference code has an error of 1 millisecond 25% of the time:

    int64_t delta = tv2->tv_sec - tv1->tv_sec;
    return delta * 1000 + (tv2->tv_usec - tv1->tv_usec) / 1000;
One way to fix it is:

    int64_t deltasec = tv2->tv_sec - tv1->tv_sec - 1;
    int64_t deltausec = tv2->tv_usec - tv1->tv_usec + 1000000;
    return deltasec * 1000 + deltausec / 1000;
1 comments

The diff is a truncation. The actual error rate is 0.5ms on average. By using a round instead of truncation, we can reduce the error to 0.25ms on average.
Well, that much is obvious. But if you are going to truncate, you should be consistent. Always truncate towards 0, not sometimes towards 0 and sometimes towards infinity.