How to Print Current Time (With Milliseconds) Using C++/C++11

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';
}

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

How do you print the current system time with milliseconds in C++11?

Using code from this answer:

#include <chrono>
#include <ctime>
#include <iostream>

template <typename Duration>
void print_time(tm t, Duration fraction) {
using namespace std::chrono;
std::printf("[%04u-%02u-%02u %02u:%02u:%02u.%03u]\n", t.tm_year + 1900,
t.tm_mon + 1, t.tm_mday, t.tm_hour, t.tm_min, t.tm_sec,
static_cast<unsigned>(fraction / milliseconds(1)));

// VS2013's library has a bug which may require you to replace
// "fraction / milliseconds(1)" with
// "duration_cast<milliseconds>(fraction).count()"
}

int main() {
using namespace std;
using namespace std::chrono;

system_clock::time_point now = system_clock::now();
system_clock::duration tp = now.time_since_epoch();

tp -= duration_cast<seconds>(tp);

time_t tt = system_clock::to_time_t(now);

print_time(*gmtime(&tt), tp);
print_time(*localtime(&tt), tp);
}

One thing to keep in mind is that the fact that the timer returns values of sub-millisecond denominations does not necessarily indicate that the timer has sub-millisecond resolution. I think Windows' implementation in VS2015 may finally be fixed, but the timer they've been using to back their chrono implementation so far has been sensitive to the OS timeBeginPeriod() setting, displaying varying resolution, and the default setting is I think 16 milliseconds.

Also the above code assumes that neither UTC nor your local timezone are offset from the epoch of std::chrono::system_clock by a fractional second value.


Example of using Howard's date functions to avoid ctime: http://coliru.stacked-crooked.com/a/98db840b238d3ce7

Get current time in milliseconds, or HH:MM:SS:MMM format

This is a cleaner solution using HowardHinnant's date library.

std::string get_time()
{
using namespace std::chrono;
auto now = time_point_cast<milliseconds>(system_clock::now());
return date::format("%T", now);
}

Getting current time with millisecond precision using put_time in C++

Here's one example using some C++11 <chrono> features. If you can use C++20, check out the new <chrono> features for more goodies or take a look at Howard Hinnants Date library.

#include <chrono>
#include <cstdint>
#include <ctime>
#include <iomanip>
#include <iostream>
#include <string>
#include <type_traits>

// A C++11 constexpr function template for counting decimals needed for
// selected precision.
template<std::size_t V, std::size_t C = 0,
typename std::enable_if<(V < 10), int>::type = 0>
constexpr std::size_t log10ish() {
return C;
}

template<std::size_t V, std::size_t C = 0,
typename std::enable_if<(V >= 10), int>::type = 0>
constexpr std::size_t log10ish() {
return log10ish<V / 10, C + 1>();
}

// A class to support using different precisions, chrono clocks and formats
template<class Precision = std::chrono::seconds,
class Clock = std::chrono::system_clock>
class log_watch {
public:
// some convenience typedefs and "decimal_width" for sub second precisions
using precision_type = Precision;
using ratio_type = typename precision_type::period;
using clock_type = Clock;
static constexpr auto decimal_width = log10ish<ratio_type{}.den>();

static_assert(ratio_type{}.num <= ratio_type{}.den,
"Only second or sub second precision supported");
static_assert(ratio_type{}.num == 1, "Unsupported precision parameter");

// default format: "%Y-%m-%dT%H:%M:%S"
log_watch(const std::string& format = "%FT%T") : m_format(format) {}

template<class P, class C>
friend std::ostream& operator<<(std::ostream&, const log_watch<P, C>&);

private:
std::string m_format;
};

template<class Precision, class Clock>
std::ostream& operator<<(std::ostream& os, const log_watch<Precision, Clock>& lw) {
// get current system clock
auto time_point = Clock::now();

// extract std::time_t from time_point
std::time_t t = Clock::to_time_t(time_point);

// output the part supported by std::tm
os << std::put_time(std::localtime(&t), lw.m_format.c_str());

// only involve chrono duration calc for displaying sub second precisions
if(lw.decimal_width) { // if constexpr( ... in C++17
// get duration since epoch
auto dur = time_point.time_since_epoch();

// extract the sub second part from the duration since epoch
auto ss =
std::chrono::duration_cast<Precision>(dur) % std::chrono::seconds{1};

// output the sub second part
os << std::setfill('0') << std::setw(lw.decimal_width) << ss.count();
}

return os;
}

int main() {
// default precision, clock and format
log_watch<> def_cp; // <= C++14
// log_watch def; // >= C++17

// alt. precision using alternative formats
log_watch<std::chrono::milliseconds> milli("%X,");
log_watch<std::chrono::microseconds> micro("%FT%T.");
// alt. precision and clock - only supported if the clock is an alias for
// system_clock
log_watch<std::chrono::nanoseconds,
std::chrono::high_resolution_clock> nano("%FT%T.");

std::cout << "def_cp: " << def_cp << "\n";
std::cout << "milli : " << milli << "\n";
std::cout << "micro : " << micro << "\n";
std::cout << "nano : " << nano << "\n";
}

Example output:

def_cp: 2019-11-21T13:44:07
milli : 13:44:07,871
micro : 2019-11-21T13:44:07.871939
nano : 2019-11-21T13:44:07.871986585

How to get current time in milliseconds?

Simply use std::chrono. The general example below times the task "of printing 1000 stars":

#include <iostream>
#include <ctime>
#include <ratio>
#include <chrono>

int main ()
{
using namespace std::chrono;

high_resolution_clock::time_point t1 = high_resolution_clock::now();

std::cout << "printing out 1000 stars...\n";
for (int i=0; i<1000; ++i) std::cout << "*";
std::cout << std::endl;

high_resolution_clock::time_point t2 = high_resolution_clock::now();

duration<double, std::milli> time_span = t2 - t1;

std::cout << "It took me " << time_span.count() << " milliseconds.";
std::cout << std::endl;

return 0;
}

Instead of printing the stars, you will place your sorting algorithm there and time measure it.


Do not forget to enable the optimization flags for your compiler, if you intend to do some benchmarking, e.g. for g++, you need -O3. This is serious, check what happened to me when I didn't do so: Why emplace_back is faster than push_back?


Ps: If your compiler doesn't support c++11, then you could look into other methods in my Time Measurements (C++).


A specific (toy) example, by using my Quicksort (C++), would be:

#include <iostream>
#include <ctime>
#include <ratio>
#include <chrono>

void quickSort(int a[], int first, int last);
int pivot(int a[], int first, int last);
void swap(int& a, int& b);
void swapNoTemp(int& a, int& b);

using namespace std;
using namespace std::chrono;

int main()
{
int test[] = { 7, -13, 1, 3, 10, 5, 2, 4 };
int N = sizeof(test)/sizeof(int);

cout << "Size of test array :" << N << endl;

high_resolution_clock::time_point t1 = high_resolution_clock::now();

// I want to measure quicksort
quickSort(test, 0, N-1);

high_resolution_clock::time_point t2 = high_resolution_clock::now();

duration<double> time_span = t2 - t1;

std::cout << "It took me " << time_span.count() << " seconds.";
std::cout << std::endl;

return 0;
}

and the output now is:

Georgioss-MacBook-Pro:~ gsamaras$ g++ -Wall -std=c++11 -O3 main.cpp 
Georgioss-MacBook-Pro:~ gsamaras$ ./a.out
Size of test array :8
It took me 3.58e-07 seconds.

It's as simple as that. Happy benchmarking! =)


EDIT:

high_resolution_clock::now() function returns time relative to which time?

From std::chrono:

Time points

A reference to a specific point in time, like one's
birthday, today's dawn, or when the next train passes. In this
library, objects of the time_point class template express this by
using a duration relative to an epoch (which is a fixed point in time
common to all time_point objects using the same clock).

where one could check this epoch and time_point example, which outputs:

time_point tp is: Thu Jan 01 01:00:01 1970

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.

How to get current timestamp in milliseconds since 1970 just the way Java gets

If you have access to the C++ 11 libraries, check out the std::chrono library. You can use it to get the milliseconds since the Unix Epoch like this:

#include <chrono>

// ...

using namespace std::chrono;
milliseconds ms = duration_cast< milliseconds >(
system_clock::now().time_since_epoch()
);

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.



Related Topics



Leave a reply



Submit