Time from gettimeofday not updating as it should
-
02-07-2021 - |
Вопрос
#include <stdio.h>
#include <sys/time.h>
int main()
{
float time;
struct timeval tv;
gettimeofday( &tv, NULL );
time = tv.tv_sec + ( tv.tv_usec / 1000000.0 );
printf( "time: %f\n", time );
return 0;
}
Running binary generated by this code repeatedly, I tend to get the same time value:
$ ./a.out
time: 1348059520.000000
$ ./a.out
time: 1348059520.000000
$ ./a.out
time: 1348059520.000000
This happens until several seconds later at which I get an updated time value.
Решение
It appears that float
is too small to contain the result of tv.tv_sec + ( tv.tv_usec / 1000000.0 )
. Use double
instead:
#include <stdio.h>
#include <sys/time.h>
int main()
{
double time;
struct timeval tv;
gettimeofday( &tv, NULL );
time = tv.tv_sec + ( tv.tv_usec / 1000000.0 );
printf( "time: %f\n", time );
return 0;
}
Другие советы
Why do you use floating point at all?
#include <stdio.h>
#include <sys/time.h>
int main (void)
{
struct timeval tv;
gettimeofday (&tv, NULL);
printf ("time: %d.%06d\n", (int)tv.tv_sec, (int)tv.tv_usec);
return 0;
}
./a.out
time: 1348067289.069908
It looks floaty, but it's inty :-) Since the microseconds value is in the range 0..999999 all you need to do is zero-pad it to 6 digits. No FP arithmetic required.
Не связан с StackOverflow