Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ chrono system time in milliseconds, time operations

I've got a small problem caused by insufficient documentation of C++11.

I'd like to obtain a time since epoch in milliseconds, or nanoseconds or seconds and then I will have to "cast" this value to another resolution. I can do it using gettimeofday() but it will be to easy, so I tried to achieve it using std::chrono.

I tried:

std::chrono::time_point<std::chrono::system_clock> now =      std::chrono::system_clock::now(); 

But I have no idea what is a resolution of obtained in this way time_point, and I don't know how to get this time as a simple unsigned long long, and I haven't any conception how to cast it to another resolution.

like image 497
Dejwi Avatar asked Feb 01 '12 02:02

Dejwi


People also ask

What is Chrono in C?

Chrono in C++ chrono is the name of a header and also of a sub-namespace: All the elements in this header (except for the common_type specializations) are not defined directly under the std namespace (like most of the standard library) but under the std::chrono namespace.

What is Time_since_epoch?

time_point::time_since_epochReturns a duration representing the amount of time between *this and the clock 's epoch.


1 Answers

You can do now.time_since_epoch() to get a duration representing the time since the epoch, with the clock's resolution. To convert to milliseconds use duration_cast:

auto duration = now.time_since_epoch(); auto millis = std::chrono::duration_cast<std::chrono::milliseconds>(duration).count(); 
like image 121
R. Martinho Fernandes Avatar answered Oct 15 '22 04:10

R. Martinho Fernandes