How do I get the current time in milliseconds in C ++?


The thing is, I have to somehow get current time of day in milliseconds in convenient format.

Example of desired output:

21 h 04 min 12 s 512 ms

I know how to get this format in seconds, but I have no idea how to get my hands on milliseconds?

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::cout << std::put_time(std::localtime(&time), "%H h %M m %S s ");
std::cout << ms.count() << " ms" << std::endl;


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

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.