reading system time to get milliseconds or nanoseconds

I saw the following structure in time.h which only has
seconds as the smallest increment.

struct tm {
        int tm_sec;  // seconds after the minute - [0,59]
        int tm_min;  // minutes after the hour - [0,59]
        int tm_hour; // hours since midnight - [0,23]
        int tm_mday; // day of the month - [1,31]
        int tm_mon;  // months since January - [0,11]
        int tm_year; // years since 1900
        int tm_wday; // days since Sunday - [0,6]
        int tm_yday; // days since January 1 - [0,365]
        int tm_isdst // daylight savings time flag

Is there another header file which has smaller time keeping?
I'm working on a win32 console app in visual c++
Who is Participating?
DanRollinsConnect With a Mentor Commented:
The _ftime function does not have a real great resolution, as domonstrated by this little test:

#include <stdio.h>
#include <sys/timeb.h>
#include <time.h>
void main()
     struct _timeb timebuffer;
     char *timeline;
     for (int j=0; j< 100; j++ ) {
          _ftime( &timebuffer );
          timeline = ctime( & ( timebuffer.time ) );

          printf( "The time is %.19s.%hu %s", timeline, timebuffer.millitm, &timeline[20] );
You'll seet a series of times that all have the same milliseconds, then it jumps by 10 or 20 milliseconds, then another series...

As for nanoseconods... forget it.  We discussed these issues at length in this thread:

In Windows, timeGetTime (the Multimedia timer fn) provides a higher-resolution timer and the QueryPerformanceCounter API provides very high resolution (e.g., for profiling code execution times).  

There are a variety of techniques to get a high-resolution timestamp.  What is your ultimate goal?  Are you just curiuus or do you have a specific need?

-- Dan
Take a look at this info from MSDN (you can get also milliseconds):

_ftime - Gets the current time.

void _ftime( struct _timeb *timeptr );

Function Required Header Compatibility
_ftime <sys/types.h> and <sys/timeb.h> Win 95, Win NT


LIBC.LIB Single thread static library, retail version
LIBCMT.LIB Multithread static library, retail version
MSVCRT.LIB Import library for MSVCRT.DLL, retail version

Return Value

_ftime does not return a value, but fills in the fields of the structure pointed to by timeptr.



Pointer to _timeb structure


The _ftime function gets the current local time and stores it in the structure pointed to by timeptr. The _timeb structure is defined in SYS\TIMEB.H. It contains four fields:


Nonzero if daylight savings time is currently in effect for the local time zone. (See _tzset for an explanation of how daylight savings time is determined.)


Fraction of a second in milliseconds.


Time in seconds since midnight (00:00:00), January 1, 1970, coordinated universal time (UTC).


Difference in minutes, moving westward, between UTC and local time. The value of timezone is set from the value of the global variable _timezone (see _tzset).


/* FTIME.C: This program uses _ftime to obtain the current
 * time and then stores this time in timebuffer.

#include <stdio.h>
#include <sys/timeb.h>
#include <time.h>

void main( void )
   struct _timeb timebuffer;
   char *timeline;

   _ftime( &timebuffer );
   timeline = ctime( & ( timebuffer.time ) );

   printf( "The time is %.19s.%hu %s", timeline, timebuffer.millitm, &timeline[20] );


The time is Tue Mar 21 15:26:41.341 1995
the simplest way for millisec is
double x = clock();
time_in_seconds = (clock() - x)/CLOCKS_PER_SEC;

include ctime for these.

the following is a high resolution timer that uses the Intel 64 bit timer register.  Its very precise!!

*Intel/Visual C++ only!!!*
(because of the asm, need intel. because of __int64 need visual, you can hack that part for other compilers)

header: (jtimer.h)


__int64 jtimer[5]; //up to 5 nested timers (call timer
//inside a call to the time, etc, like time whole
//program, then subroutines a,b,c ...)

#define mhz 1000000 //one million hertz
#define machine_speed 1000*mhz //your speed here!!
inline void start_time(int dx);
inline void elapsed_time(int dx);



inline void start_time(int dx)
// cpu instructions
#define rdtsc __asm __emit 0Fh __asm __emit 031h
#define cpuid __asm __emit 0Fh __asm __emit 0A2h

__int64 ts = 0; //working variable

__asm push EAX
__asm push EDX
//cpuid  //other info
rdtsc    //read time stamp register

__asm mov dword ptr ts, EAX //low bits
__asm and EDX, 07fffffffh //63 bit int, sign removed
__asm mov dword ptr ts+4,EDX //high bits

__asm pop EDX
__asm pop EAX

#undef rdtsc
#undef cpuid
jtimer[dx] = ts;

inline void elapsed_time(int dx)
#define rdtsc __asm __emit 0Fh __asm __emit 031h
#define cpuid __asm __emit 0Fh __asm __emit 0A2h

__int64 ts = 0;

__asm push EAX
__asm push EDX
//cpuid  //other info
rdtsc    //read time stamp register

__asm mov dword ptr ts, EAX //low bits
__asm and EDX, 07fffffffh //63 bit int, sign removed
__asm mov dword ptr ts+4,EDX //high bits

__asm pop EDX
__asm pop EAX

#undef rdtsc
#undef cpuid
ts -=jtimer[dx];
printf("time is %f seconds\n", (double)(ts)/(double)(machine_speed));

Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

The GetSystemTime function retrieves the current system date and time. The system time is expressed in Coordinated Universal Time (UTC).

VOID GetSystemTime(
  LPSYSTEMTIME lpSystemTime   // address of system time structure
Pointer to a SYSTEMTIME structure to receive the current system date and time.

typedef struct _SYSTEMTIME {  // st
    WORD wYear;
    WORD wMonth;
    WORD wDayOfWeek;
    WORD wDay;
    WORD wHour;
    WORD wMinute;
    WORD wSecond;
    WORD wMilliseconds;
2 mitchguy
I expect that you need milliseconds for relative time.
Often I use GetTickCount().

DWORD dwStart = GetTickCount();

// Stop if this has taken too long
if( GetTickCount() - dwStart >= TIMELIMIT ){

For best result you can use "High-resolution performance counter" as DanRollins suggest:
QueryPerformanceFrequency, QueryPerformanceCounter.

For Windows NT try to use "The Performance Data Helper (PDH) library":
In some cases, you can also use GetLocalTime( ),which can
support your local machine current time .
For super fine resolution under Windows, use the QueryPerformanceCounter/QueryPerformanceFrequency API calls.

QueryPerformanceCounter (&before);
// Some code
QueryPerformanceCounter (&after);

// Calculate the diference.
LARGE_INTEGER diff = after-before;

QueryPerformanceFrecuency (&freq);
// The frequency is on seconds thus divide by 1000
freq = freq / 1000;

LARGE_INTEGER milliseconds = diff*freq;

Hope this helps
mitchguyAuthor Commented:
The QueryPerformanceCounter seems to work the best of all
of the suggested methods. My goal was to get the frame rate of my openGL display loop to run at 6ofps.
Most of the previous solutions seem to be for Windows systems. How would I go about measuring Milliseconds (needed for fixed frame rates for animations, seconds intime.h are too slow) in C++ cross-platform (Linux and Windows). Glut doesn't seem to carry any time capability so I assume I will have to use #defines to detect the OS and run seperate code sections?
Hello - does the QueryPerformanceCounter code work on a Windows 2000 system?

Under the Help for MSDN, it mentions Windows 95 and Windows NT - just want to make sure it applies to Windows 2000.

To use the above code in Visual C++, I just need to include "Windows.h"   -  is this correct?

Also, regarding the above, can a "LARGE_INTEGER" be cast into the "double" type?
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.