Solved

reading system time to get milliseconds or nanoseconds

Posted on 2002-05-20
13
114,761 Views
Last Modified: 2011-08-18
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++
0
Comment
Question by:mitchguy
13 Comments
 
LVL 11

Expert Comment

by:dimitry
ID: 7023263
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

Libraries

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.

Parameter

timeptr

Pointer to _timeb structure

Remarks

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:

dstflag

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

millitm

Fraction of a second in milliseconds.

time

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

timezone

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

Example

/* 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] );
}

Output

The time is Tue Mar 21 15:26:41.341 1995
0
 
LVL 49

Accepted Solution

by:
DanRollins earned 50 total points
ID: 7023391
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:

http://www.experts-exchange.com/questions/Q.20185363.html

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
0
 
LVL 2

Expert Comment

by:jonnin
ID: 7023765
the simplest way for millisec is
double x = clock();
code
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)

#include<cstdio>

__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);

_________________________________________________
cpp

#include"jtimer.h"

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));
}



0
 
LVL 86

Expert Comment

by:jkr
ID: 7023844
GetSystemTime
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
);
 
Parameters
lpSystemTime
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;
} SYSTEMTIME;
0
 
LVL 16

Expert Comment

by:AlexNek
ID: 7024716
2 mitchguy
I expect that you need milliseconds for relative time.
Often I use GetTickCount().

DWORD dwStart = GetTickCount();

for..
...
// Stop if this has taken too long
if( GetTickCount() - dwStart >= TIMELIMIT ){
  break;
}

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":
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnperfmo/html/msdn_pdhlib.asp
0
 

Expert Comment

by:yinzuquan
ID: 7025979
In some cases, you can also use GetLocalTime( ),which can
support your local machine current time .
0
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 
LVL 2

Expert Comment

by:zechis
ID: 7027374
For super fine resolution under Windows, use the QueryPerformanceCounter/QueryPerformanceFrequency API calls.
0
 
LVL 1

Expert Comment

by:thegroup
ID: 7027589
LARGE_INTEGER before;
LARGE_INTEGER after;

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

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

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

LARGE_INTEGER milliseconds = diff*freq;

Hope this helps
0
 

Author Comment

by:mitchguy
ID: 7034846
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.
0
 

Expert Comment

by:Trevor_Arsenault
ID: 10516066
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?
0
 

Expert Comment

by:bengssh
ID: 13059800
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?

Thanks,
--Sharon
0
 

Expert Comment

by:bengssh
ID: 13059808
Also, regarding the above, can a "LARGE_INTEGER" be cast into the "double" type?
0

Featured Post

Do You Know the 4 Main Threat Actor Types?

Do you know the main threat actor types? Most attackers fall into one of four categories, each with their own favored tactics, techniques, and procedures.

Join & Write a Comment

When writing generic code, using template meta-programming techniques, it is sometimes useful to know if a type is convertible to another type. A good example of when this might be is if you are writing diagnostic instrumentation for code to generat…
Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
The goal of the video will be to teach the user the concept of local variables and scope. An example of a locally defined variable will be given as well as an explanation of what scope is in C++. The local variable and concept of scope will be relat…
The viewer will learn how to clear a vector as well as how to detect empty vectors in C++.

705 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

16 Experts available now in Live!

Get 1:1 Help Now