ronan
ronan

Reputation: 4672

Capturing a time in milliseconds

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?

Upvotes: 13

Views: 61159

Answers (7)

Howard Hinnant
Howard Hinnant

Reputation: 219488

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

Upvotes: 1

MauriRamone
MauriRamone

Reputation: 513

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

Upvotes: 1

neuro
neuro

Reputation: 15210

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

Upvotes: 23

user3762106
user3762106

Reputation: 6217

//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;

Upvotes: 17

Yuval Baror
Yuval Baror

Reputation: 21

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

Upvotes: 2

Chris Ballance
Chris Ballance

Reputation: 34367

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.

Upvotes: 4

Eric
Eric

Reputation: 6446

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.

Upvotes: 2

Related Questions