13

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?

unwind
  • 391,730
  • 64
  • 469
  • 606
ronan
  • 4,492
  • 13
  • 47
  • 67
  • 4
    possible duplicate of [How to get current timestamp in milliseconds since 1970 just the way Java gets](http://stackoverflow.com/questions/19555121/how-to-get-current-timestamp-in-milliseconds-since-1970-just-the-way-java-gets) – Ciro Santilli OurBigBook.com Sep 30 '15 at 09:06

7 Answers7

23

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

In Linux you can use

#include <sys/time.h>

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

timeval has microsecond precision.

In Windows you can use:

#include <Windows.h>

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

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

neuro
  • 14,948
  • 3
  • 36
  • 59
17

//C++11 Style:

cout << "Time in Milliseconds =" << 
 chrono::duration_cast<chrono::milliseconds>(chrono::steady_clock::now().time_since_epoch()).count() 
 << std::endl;

cout << "Time in MicroSeconds=" << 
 chrono::duration_cast<chrono::microseconds>(chrono::steady_clock::now().time_since_epoch()).count() 
 << std::endl;
user3762106
  • 5,787
  • 1
  • 13
  • 7
4

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
  • 33,810
  • 26
  • 104
  • 151
2

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
  • 6,364
  • 1
  • 32
  • 49
2

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

bluish
  • 26,356
  • 27
  • 122
  • 180
1

In Ubuntu 16.04 this worked for me...

const std::string currentDateTime() {
   char            fmt[64], buf[64];
   struct timeval  tv;
   struct tm       *tm;

   gettimeofday(&tv, NULL);
   tm = localtime(&tv.tv_sec);
   strftime(fmt, sizeof fmt, "%Y-%m-%d %H:%M:%S.%%06u", tm);
   snprintf(buf, sizeof buf, fmt, tv.tv_usec);
   return buf;
}

Then, with...

std::cout << currentDateTime();

I get...

2016-12-29 11:09:55.331008
pacholik
  • 8,607
  • 9
  • 43
  • 55
MauriRamone
  • 469
  • 1
  • 3
  • 21
1

New answer for old question using C++11 or C++14 and this free, open-source library:

#include "tz.h"
#include <iostream>

int
main()
{
    using namespace date;
    using namespace std;
    using namespace std::chrono;
    auto now = make_zoned(current_zone(), floor<milliseconds>(system_clock::now()));
    cout << format("%e/%m/%Y %T", now) << '\n';
}

This just output for me:

16/01/2017 15:34:32.167

which is my current local date and time to millisecond precision. By eliminating the floor<milliseconds>() you will automatically get whatever precision your system_clock has.

If you wanted the result as a UTC timestamp instead of a local timestamp, it is even easier:

    auto now = floor<milliseconds>(system_clock::now());
    cout << format("%e/%m/%Y %T", now) << '\n';

And if you want a UTC timestamp and you aren't picky about the precision or the format, you can just:

cout << system_clock::now() << '\n';

which just output for me:

2017-01-16 20:42:11.267245
Howard Hinnant
  • 206,506
  • 52
  • 449
  • 577