Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accurate conversion between timeval and microseconds

Tags:

c

linux

time

glibc

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 ?

like image 371
Donald Wu Avatar asked Nov 19 '25 01:11

Donald Wu


1 Answers

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;
}
like image 63
chqrlie Avatar answered Nov 20 '25 15:11

chqrlie



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!