4

In a program that accumulates struct timespec deltas, I am doing the following logic:

struct timespec accu, start, stop;

for (...) {
    // record start
    // perform some logic
    // record stop

    accu.tv_sec += stop.tv_sec - start.tv_sec;
    accu.tv_nsec += stop.tv_nsec - start.tv_nsec;
    if (accu.tv_nsec >= 1000000000L) {
        accu.tv_nsec -= 1000000000L;
        ++accu.tv_sec;
    }
} // end for loop

However, when I print the result using:

printf("%lld.%.9ld\n", (long long) accu.tv_sec, accu.tv_nsec);

I sometime see results like: 1.-611075708

What am I doing wrong to have a negative value in accu.tv_nsec?

Note: start & stop retrieved with clock_gettime().

1
  • Think about what happens when stop.tv_nsec < start.tv_nsec. You get a negative value which you accumulate into the accumulator. If this negative accumuland drops the accumulator below zero, it's of course not going to be >= 1000000000L. You also need the wraparound logic in the other direction. Jun 24, 2014 at 14:48

2 Answers 2

5

Convert struct timespec to a uint64_t number of nanoseconds since epoch and take deltas between those and accumulate them easily. E.g.:

#include <time.h>
#include <stdint.h>

inline uint64_t as_nanoseconds(struct timespec* ts) {
    return ts->tv_sec * (uint64_t)1000000000L + ts->tv_nsec;
}

int main() {
    struct timespec start, stop;
    uint64_t accu_nsec = 0;

    for (...) {
        // record start
        // perform some logic
        // record stop

        accu_nsec += as_nanoseconds(&stop) - as_nanoseconds(&start);
    } // end for loop
}
3
  • Answer accepted, thanks, however I will rather use: accu += (stop.tv_sec - start.tv_sec) * 1000000000L + stop.tv_nsec - start.tv_nsec; which will save one arithmetic operation per accumulation. Jun 24, 2014 at 15:48
  • 2
    Be careful to always cast the result of (stop.tv_sec - start.tv_sec) into a 64-bit int, otherwise the compiler might do a 32-bit int, and when you multiply by 1000000000 you will overflow. Jun 24, 2014 at 15:58
  • @PatrickAllaert It depends on the compiler, clang generates same code for both versions: gcc.godbolt.org/z/13ajxY Jul 17, 2020 at 15:06
3

You can't simply add the times like this without proper overflow/underflow handling of the second addition. Example: start = 1.99...s, stop = 2.01...s

This gives us:

accu.tv_sec += 2 - 1 = 1;
accu.tv_nsec += 01... - 99.. = -98...;

Therefore, you have to use a temporary variable to calculate nsec. If it's <0, then you need to substract 1s and add 1000000000L to nsec.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.