Skrevet av Emne: C++ unix timestamp in seconds as a double with millisecond precision  (Lest 14998 ganger)

Utlogget Floyd-ATC

  • Livstidsdiktator
  • Administrator
  • Guru
  • *****
  • Innlegg: 542
  • Karma: +12/-0
    • MSN Messenger - floyd@atc.no
    • Vis profil
    • floyd.atc.no
    • E-post
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: [Velg]
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);
}

Sample output:
Kode: [Velg]
1577703729.406= 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.


-Floyd.

--
Det finnes 10 typer mennesker;
de som forstår binærtall, de som ikke gjør det, og de som forstår Grey code.