Reputation: 12459
#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.
Upvotes: 3
Views: 5410
Reputation: 72746
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.
Upvotes: 3
Reputation: 12459
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;
}
Upvotes: 4