How can I get current time of day in milliseconds in C++? -
the thing is, have somehow current time of day in milliseconds in convenient format.
example of desired output:
21 h 04 min 12 s 512 ms
i know how format in seconds, have no idea how hands on milliseconds?
using portable std::chrono
auto = 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
note systems clocks doesn't support millisecond resolution
as pointed out @user4581301, on systems std::system_clock might not have enough resolution accurately representing current time in milliseconds. if case, try using std::high_resolution_clock calculating number of milliseconds since last second. ensure highest available resolution provided implementation.
taking time 2 clocks inevitably lead 2 separate points in time (however small time difference be). keep in mind using separate clock calculating milliseconds not yield perfect synchronization between second, , millisecond periods.
// use system clock time. auto = std::chrono::system_clock::now(); /* small amount of time passes between storing time points. */ // use separate high resolution clock 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 no guarantee tick events of std::high_resolution_clock , std::system_clock synchronized, , because of millisecond period might not in sync periodic update of current second given system clock.
because of these reasons, using separate high resolution clock millisecond resolution should not used when <1 second precision critical.
Comments
Post a Comment