Linux, C, Time in Milliseconds


REFERENCE: man ftime

Milliseconds

The only tricky part here is getting the milliseconds. If you do a man on ftime ("man ftime") you see this
Linux                      24 July 1993                         1
NAME
       ftime - return date and time

SYNOPSIS
       #include 

       int ftime(struct timeb *tp);

DESCRIPTION
       Return  current  date and time in tp, which is declared as
       following:

                 struct timeb {
                      time_t   time;
                      unsigned short millitm;
                      short    timezone;
                      short    dstflag;
                 };

RETURN VALUE
       This function always returns 0.

NOTES
       Under Linux, this function is not implemented in a compat-
       ibility library instead of in the kernel.

CONFORMING TO
       V7, BSD 4.3
       Under  BSD 4.3, this call is obsoleted by gettimeofday(2).

SEE ALSO
       time(2)

The key thing to note is the "millitm" as the second thing in that structure. At first I thought it was Military Time, meaning 24-hour time, but it is actually milliseconds. The second thing to note, is that on Linux the "time_t" is typedef'd to a long. This you can observer by grepping around in the .h files until you see where time_t is defined.

Therefore, the following program will spit out the time in seconds since Jan 1st 1970 and will append the milliseconds.


#include 

void main(int argc,char *argv[])
{
  struct timeb tp;
  
  while (1)
  {
    ftime(&tp);
    printf("time = %ld.%d\n",tp.time,tp.millitm);
  }
 
}

There are lots of things you can do to convert the seconds to things like the date, and most of the time functions are dedicated to this. Do a man on time, ctime, date, strftime and some others and you'll figure it out pretty quick. None of them talk about milliseconds however, hence this page.

Return to Gene's Home Page
Return to Gene's Random Unix Crap