Teknisk > Generelt teknisk

C++ unix timestamp in seconds as a double with millisecond precision

(1/1)

Floyd-ATC:
This question seems to be a FAQ that nobody seems to understand or answer correctly, instead answering a lot of other questions dealing with clock irregularity and loss of precision when dealing with nanoseconds. Neither of which matter when you're using double precision and only want milliseconds for moving a game object on the screen or whatever and the occasional jitter or skew from a timesync event isn't going to bring about the end of civilization as we know it.

So here's how I finally managed to solve it with my fairly limited C++ skill:

--- Kode: ---double now() {
  auto time = std::chrono::system_clock::now().time_since_epoch();
  std::chrono::seconds seconds = std::chrono::duration_cast< std::chrono::seconds >(time);
  std::chrono::milliseconds ms = std::chrono::duration_cast< std::chrono::milliseconds >(time);
  return (double) seconds.count() + ((double) (ms.count() % 1000)/1000.0);
}

--- Slutt kode ---

Sample output:

--- Kode: ---1577703729.406
--- Slutt kode ---
= Unix timestamp in seconds as a double with millisecond precision.

There you have it.

Useful in pretty much any formula that deals with time in seconds, yet somehow not documented anywhere and unbelievably verbose for a modern library supposedly written specifically to deal exclusively with time.

Navigering

[0] Oversikt

Skift til full visning