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

tshepang
  • 12,111
  • 21
  • 91
  • 136
  • `int main()` is undefined behavior. This is C, where `()` is not the same as `(void)`. – Jens Sep 20 '12 at 07:20

2 Answers2

4

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;
}
tshepang
  • 12,111
  • 21
  • 91
  • 136
  • 3
    Not only 'appears' — that is precisely the trouble. `float` can store 6-7 decimal digits; the time stamp at second level needs 10 decimal digits in the integer portion of the time, so to get 6 decimal places too, you need 16 decimal digits, which is just in range of `double` (assuming IEEE 754 floating point arithmetic). – Jonathan Leffler Sep 19 '12 at 13:40
  • +1 _Never_ put time in a `float`. Always use a `double` or `time_t`, as I've learnt the hard way. P.s. With gcc's (and other compiler's) shadow warnings, one shouldn't use `time` as a variable name. – Joseph Quinsey Feb 14 '14 at 23:52
3

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.

Jens
  • 69,818
  • 15
  • 125
  • 179
  • 1
    By the way, I like this answer MUCH better as a way to accomplish what OP wants, but Tshepang's answer better explains the mechanism of the specific problem OP encountered. +1 to both, anyway. – R.. GitHub STOP HELPING ICE Sep 19 '12 at 18:03