views:

1052

answers:

4

The following piece of code is used to print the time in the logs:

#define PRINTTIME() struct tm  * tmptime;
time_t     tmpGetTime;
time(&tmpGetTime);
tmptime = localtime(&tmpGetTime);
cout << tmptime->tm_mday << "/" <<tmptime->tm_mon+1 << "/" << 1900+tmptime->tm_year << " " << tmptime->tm_hour << ":" << tmptime->tm_min << ":" << tmptime->tm_sec<<">>";

Is there any way to add milliseconds to this?

+2  A: 

You need a timer with a higher resolution in order to capture milliseconds. Try this:

int cloc = clock();
//do something that takes a few milliseconds
cout << (clock() - cloc) << endl;

This is of course dependent on your OS.

Chris Ballance
Hum I think that clock() returns a clock_t which represent a clock unit. Moreover on linux it does not achieve a ms precision AFAIK
neuro
+1  A: 

The high resolution timers are usually gettimeofday on Linux style platforms and QueryPerformanceCounter on Windows.

You should be aware that timing the duration of a single operation (even with a high resolution timer) will not yield accurate results. There are too many random factors at play. To get reliable timing information, you should run the task to be timed in a loop and compute the average task time. For this type of timing, the clock() function should be sufficient.

Eric
+5  A: 

To have millisecond precision you have to use system calls specific to your OS.

In Linux you can use

timeval tv;
gettimeofday(&tv, 0);
// then convert struct tv to your needed ms precision

timeval has microsecond precision.

In Windows you can use:

SYSTEMTIME st;
GetSystemTime(&st);
// then convert st to your precision needs

Of course you can use Boost to do that for you :)

neuro
Thanks a lot I will try this
ronan
A: 

If you don't want to use any OS-specific code, you can use the ACE package which supplies the ACE_OS::gettimeofday function for most standard operating systems. For example:

ACE_Time_Value startTime = ACE_OS::gettimeofday();

do_something();

ACE_Time_Value endTime = ACE_OS::gettimeofday();

cout << "Elapsed time: " << (endTime.sec() - startTime.sec()) << " seconds and " << double(endTime.usec() - startTime.usec()) / 1000 << " milliseconds." << endl;

This code will work regardless of your OS (as long as ACE supports this OS).

Yuval Baror