How to implement timespec drives?

In the program that accumulates the delta struct timespec, I do 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);

Do I ever see results like: 1.-611075708

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

Note: startand stopextracted using clock_gettime().

+4
source share
2 answers

Convert struct timespecto the number of uint64_tnanoseconds from the era and take the deltas between them and carefully copy them. For instance:.

#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
}
+5
source

, , / . : start = 1.99... s, stop = 2.01... s

:

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

nsec . < 0, 1s 1000000000L nsec.

+3

Source: https://habr.com/ru/post/1545854/


All Articles