This has nothing to do with the mythology of clock_gettime
's monotonic clock not actually being monotonic (which probably has a basis in reality, but which was never well documented and probably fixed a long time ago). It's just a bug in your program. tv_nsec
is the nanoseconds portion of a time value that's stored as two fields:
tv_sec
- whole secondstv_nsec
- nanoseconds in the range 0 to 999999999
Of course tv_nsec
is going to jump backwards from 999999999 to 0 when tv_sec
increments. To compute differences of timespec
structs, you need to take 1000000000 times the difference in seconds and add that to the difference in nanoseconds. Of course this could quickly overflow if you don't convert to a 64-bit type first.