Std::chrono
lastmod 2018-08-17created 2015-03-1916 edits
Include the standard header chrono to define classes and functions that represent and manipulate durations and time instants.
Classes
-
duration: Describes a type that holds a time interval. -
time_point: Describes a type that represents a point in time.
Structure
-
common_type: Describes specializations of the template class common_type for instantiations of duration and time_point. -
duration_values: Provides specific values for the duration template parameter Rep. -
steady_clock: Represents a steady clock. -
system_clock: Represents a clock type that is based on the system's real-time clock. -
treat_as_floating_point: Specifies whether a type can be treated as a floating-point type.
Functions
-
duration_cast: Casts a duration object to a specified type. -
time_point_cast: Casts a time_point object to a specified type.
Now Milliseconds
To get the current time in milliseconds:
unsigned long milliseconds_since_epoch =
std::chrono::system_clock::now().time_since_epoch() /
std::chrono::milliseconds(1);
OR:
auto duration = now.time_since_epoch();
auto millis = std::chrono::duration_cast<std::chrono::milliseconds>(duration).count();
time_t convert
using namespace std;
using namespace chrono;
// time_point -> time_t
std::chrono::system_clock::time_point currTimePoint = system_clock::now();
time_t currTime = system_clock::to_time_t(currTimePoint);
// time_t -> time_point
time_t currTime = time(nullptr);
system_clock::time_point currTimePoint = system_clock::from_time_t(currTime);
Print timespemp
#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);
}
Category
See also
Favorite site
- Date and time utilities
- [Recommended] Sukkarak's Programming Stories: C++11 chrono 1
- MSDN: chrono
-
The C++ Standard Library: Utilities - Clocks and Timers(this page is dangerous, so read the PDF if possible)2 - How to print current time (with milliseconds) using C++ / C++11