I found it is also very easy to use
clock_gettime the wrong way. I used only the nanoseconds field (
tv_nsec) for days, getting occasional timeouts that I could not explain… The cause was that the nanoseconds wrapped around, combined with my other check (max iterations or something) catching most of the cases. The solution (obviously for those who understand
clock_gettime) was to convert both the seconds and the nanoseconds to milliseconds (microseconds would do too, I guess), and sum them. There may also be a simpler solution.
Update: Apparently, my solution was not all that good in practice. I don’t know why, but it still gave some negative values. Just using
clock() may be a better alternative. That is also a standard function.
Update in 2020:
clock() did not get rid of timeouts. Negative values on
clock_gettime seems like an overflow issue. Update again: It looks like I am back in business, using
clock_gettime. No timeouts observed in hundreds of battles.