Get Current Time in Milliseconds Using C++ and Boost

Get current time in milliseconds using C++ and Boost

You can use boost::posix_time::time_duration to get the time range. E.g like this

boost::posix_time::time_duration diff = tick - now;
diff.total_milliseconds();

And to get a higher resolution you can change the clock you are using. For example to the boost::posix_time::microsec_clock, though this can be OS dependent. On Windows, for example, boost::posix_time::microsecond_clock has milisecond resolution, not microsecond.

An example which is a little dependent on the hardware.

int main(int argc, char* argv[])
{
boost::posix_time::ptime t1 = boost::posix_time::second_clock::local_time();
boost::this_thread::sleep(boost::posix_time::millisec(500));
boost::posix_time::ptime t2 = boost::posix_time::second_clock::local_time();
boost::posix_time::time_duration diff = t2 - t1;
std::cout << diff.total_milliseconds() << std::endl;

boost::posix_time::ptime mst1 = boost::posix_time::microsec_clock::local_time();
boost::this_thread::sleep(boost::posix_time::millisec(500));
boost::posix_time::ptime mst2 = boost::posix_time::microsec_clock::local_time();
boost::posix_time::time_duration msdiff = mst2 - mst1;
std::cout << msdiff.total_milliseconds() << std::endl;
return 0;
}

On my win7 machine. The first out is either 0 or 1000. Second resolution.
The second one is nearly always 500, because of the higher resolution of the clock. I hope that help a little.

C++ Boost: Get time with milliseconds

You can use boost::posix_time::microsec_clock :

 std::string isoString = boost::posix_time::to_iso_string(boost::posix_time::microsec_clock::universal_time());
std::string date = isoString.substr(0,8);
std::string time = isoString.substr(9,20);

How to get GMT time in milliseconds using boost Date_Time?

There's nothing built-in that I can see, but as usual, it's trivial to implement:

boost::posix_time::time_duration::tick_type milliseconds_since_epoch()
{
using boost::gregorian::date;
using boost::posix_time::ptime;
using boost::posix_time::microsec_clock;

static ptime const epoch(date(1970, 1, 1));
return (microsec_clock::universal_time() - epoch).total_milliseconds();
}

How can I get current time of day in milliseconds in C++?

Using the portable std::chrono

auto now = std::chrono::system_clock::now();
auto time = std::chrono::system_clock::to_time_t(now);
auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(now.time_since_epoch()) -
std::chrono::duration_cast<std::chrono::seconds>(now.time_since_epoch());

std::cout << std::put_time(std::localtime(&time), "%H h %M m %S s ");
std::cout << ms.count() << " ms" << std::endl;

Output:

21 h 24 m 22 s 428 ms

Live example


Note for systems with clocks that doesn't support millisecond resolution

As pointed out by @user4581301, on some systems std::system_clock might not have enough resolution for accurately representing current time in milliseconds. If that is the case, try using std::high_resolution_clock for calculating the number of milliseconds since the last second. This will ensure the highest available resolution provided by your implementation.

Taking the time from two clocks will inevitably lead you to get two separate points in time (however small the time difference will be). So keep in mind that using a separate clock for calculating the milliseconds will not yield perfect synchronization between the second, and millisecond periods.

// Use system clock for time.
auto now = std::chrono::system_clock::now();

/* A small amount of time passes between storing the time points. */

// Use separate high resolution clock for calculating milliseconds.
auto hnow = std::chrono::high_resolution_clock::now();
auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(hnow.time_since_epoch()) -
std::chrono::duration_cast<std::chrono::seconds>(hnow.time_since_epoch());

Also, there seems to be no guarantee that the tick events of std::high_resolution_clock and std::system_clock are synchronized, and because of this the millisecond period might not be in sync with the periodic update of the current second given by the system clock.

Because of these reasons, using a separate high resolution clock for millisecond resolution should not be used when <1 second precision is critical.

Get time with milliseconds in C++17?

So just print the milliseconds from the timepoint...

const auto ms = std::chrono::time_point_cast<std::chrono::milliseconds>(currentDateTime).time_since_epoch().count() % 1000;
std::clog << std::put_time(¤tDateTimeLocalTime, "%Y%m%d_%H%M%S")
<< "." << std::setfill('0') << std::setw(3) << ms << std::endl;

How can i get current time with millisecond in C++11

You already have current time at std::chrono::system_clock::now() call.

How to get the current time in milliseconds in C Programming

quick answer

#include<stdio.h>   
#include<time.h>

int main()
{
clock_t t1, t2;
t1 = clock();
int i;
for(i = 0; i < 1000000; i++)
{
int x = 90;
}

t2 = clock();

float diff = ((float)(t2 - t1) / 1000000.0F ) * 1000;
printf("%f",diff);

return 0;
}

How to print current time (with milliseconds) using C++ / C++11

You can use Boost's Posix Time.

You can use boost::posix_time::microsec_clock::local_time() to get current time from microseconds-resolution clock:

boost::posix_time::ptime now = boost::posix_time::microsec_clock::local_time();

Then you can compute time offset in current day (since your duration output is in the form <hours>:<minutes>:<seconds>.<milliseconds>, I'm assuming they are calculated as current day offset; if they are not, feel free to use another starting point for duration/time interval):

boost::posix_time::time_duration td = now.time_of_day();

Then you can use .hours(), .minutes(), .seconds() accessors to get the corresponding values.

Unfortunately, there doesn't seem to be a .milliseconds() accessor, but there is a .total_milliseconds() one; so you can do a little subtraction math to get the remaining milliseconds to be formatted in the string.

Then you can use sprintf() (or sprintf()_s if you are interested in non-portable VC++-only code) to format those fields into a raw char buffer, and safely wrap this raw C string buffer into a robust convenient std::string instance.

See the commented code below for further details.

Output in console is something like:

11:43:52.276


Sample code:

///////////////////////////////////////////////////////////////////////////////

#include <stdio.h> // for sprintf()

#include <iostream> // for console output
#include <string> // for std::string

#include <boost/date_time/posix_time/posix_time.hpp>

//-----------------------------------------------------------------------------
// Format current time (calculated as an offset in current day) in this form:
//
// "hh:mm:ss.SSS" (where "SSS" are milliseconds)
//-----------------------------------------------------------------------------
std::string now_str()
{
// Get current time from the clock, using microseconds resolution
const boost::posix_time::ptime now =
boost::posix_time::microsec_clock::local_time();

// Get the time offset in current day
const boost::posix_time::time_duration td = now.time_of_day();

//
// Extract hours, minutes, seconds and milliseconds.
//
// Since there is no direct accessor ".milliseconds()",
// milliseconds are computed _by difference_ between total milliseconds
// (for which there is an accessor), and the hours/minutes/seconds
// values previously fetched.
//
const long hours = td.hours();
const long minutes = td.minutes();
const long seconds = td.seconds();
const long milliseconds = td.total_milliseconds() -
((hours * 3600 + minutes * 60 + seconds) * 1000);

//
// Format like this:
//
// hh:mm:ss.SSS
//
// e.g. 02:15:40:321
//
// ^ ^
// | |
// 123456789*12
// ---------10- --> 12 chars + \0 --> 13 chars should suffice
//
//
char buf[40];
sprintf(buf, "%02ld:%02ld:%02ld.%03ld",
hours, minutes, seconds, milliseconds);

return buf;
}

int main()
{
std::cout << now_str() << '\n';
}

///////////////////////////////////////////////////////////////////////////////

Formatting time in milliseconds using boost::date_time library

You need to add the duration to a time object first, and then output it like this:

boost::posix_time::time_facet* facet = new boost::posix_time::time_facet("%Y%m%d %H:%M:%S.%f");
std::stringstream date_stream;
date_stream.imbue(std::locale(date_stream.getloc(), facet));
date_stream << boost::posix_time::microsec_clock::universal_time();

output:

20100326 12:02:08.024820

Tested with boost 1.41



Related Topics



Leave a reply



Submit