I'm sure the answer is simple, but I don't quite get it. I'm trying to calculate the delta between two struct timespec using this code:
struct timespec start, finish, diff;
int ndiff;
/* Structs are filled somewhere else */
diff.tv_sec = finish.tv_sec - start.tv_sec;
ndiff = finish.tv_nsec - start.tv_nsec;
if (ndiff < 0) {
diff.tv_sec--;
ndiff = 1L - ndiff;
}
diff.tv_nsec = ndiff;
printf("Elapsed time: %ld.%ld seconds.\n", diff.tv_sec, diff.tv_nsec);
However, the output is always something like Elapsed time: 0.300876000 seconds. which seems to indicate that I'm losing the last three digits of the nanoseconds (since those shouldn't always be zero). Can someone point out what's causing that?
The code's clock reported precision is 1000 ns. @John Bollinger @rici
and/or
diff.tv_secis not necessarily along. Use a matching specifier.Also, incorrect "borrow" math when updating the
ndiff.Even better, drop the
int diffvariable.Should
finishoccur beforestart, then other code may be desired to keep the 2 members ofdiffwith the same sign.