Search code examples
clinuxtimeglibc

Accurate conversion between timeval and microseconds


Say t = 8.376600;

If I calculate tv by:

tv->tv_sec = (long) floor (time);
tv->tv_usec = (long) ((time - tv->tv_sec) * 1000000);

Then tv->tv_sec == 8 and tv->tv_usec == 376599.

printf("%f %ld.%06ld\n", time, tv->tv_sec, tv->tv_usec); prints 8.376600 8.376599.

Is there any simple way I can make the two outputs identical ?


Solution

  • In your code, you round the value down whereas printf rounds it to the nearest microsecond.

    Here is an alternative version:

    #include <math.h>
    #include <time.h>
    
    void set_timespec(struct timespec *tv, double time) {
        long long usec = round(time * 1000000);
        tv->tv_sec = usec / 1000000;
        tv->tv_usec = usec % 1000000;
    }