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?
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.
//C++11 Style:
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:This code will work regardless of your OS (as long as ACE supports this OS).
To have millisecond precision you have to use system calls specific to your OS.
In Linux you can use
timeval
has microsecond precision.In Windows you can use:
Of course you can use Boost to do that for you :)
New answer for old question using C++11 or C++14 and this free, open-source library:
This just output for me:
which is my current local date and time to millisecond precision. By eliminating the
floor<milliseconds>()
you will automatically get whatever precision yoursystem_clock
has.If you wanted the result as a UTC timestamp instead of a local timestamp, it is even easier:
And if you want a UTC timestamp and you aren't picky about the precision or the format, you can just:
which just output for me:
You need a timer with a higher resolution in order to capture milliseconds. Try this:
This is of course dependent on your OS.