문제

#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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top