92

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.

Cœur
  • 37,241
  • 25
  • 195
  • 267
Dejwi
  • 4,393
  • 12
  • 45
  • 74

1 Answers1

152

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();
Flow
  • 23,572
  • 15
  • 99
  • 156
R. Martinho Fernandes
  • 228,013
  • 71
  • 433
  • 510
  • 23
    +1. More information here (it is nearly a tutorial): http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2008/n2661.htm – Howard Hinnant Feb 01 '12 at 02:56
  • 1
    @Howard thanks! Now I have some place to point people to when they tell me they don't undersand ``. – R. Martinho Fernandes Feb 01 '12 at 20:59
  • 5
    If you aren't including the shortcut headers: auto duration = std::chrono::system_clock::now().time_since_epoch(); – Wheezil Jul 27 '20 at 17:45
  • 4
    @R. Martinho Fernandes Do you have some place to point people to when they tell you they don' understand how the C++ Standards Committee can so consistently produce insanely difficult application interfaces that require you to read 40 pages of documentation written by some guy on the internet to do what can be done in one line in a sensible language? – Robin Davies Mar 23 '22 at 04:45
  • 1
    Or you could use `std::chrono::time_point_cast(std::chrono::system_clock::now())` to get a `std::chrono::time_point`. – Ludovic Kuty Mar 31 '23 at 09:28