Time in C++: Inter-Clock Conversions, Epochs, and Durations

(sandordargo.com)

21 points | by ibobev 2 days ago

3 comments

  • barishnamazov 57 minutes ago
    I built a local competitive programming judge a while back where I fell into the exact trap of manually correlating steady_clock and system_clock.

    I was timestamping everything using steady_clock to strictly enforce the time limits, and then just applied a calculated offset to convert that to wall time for the "Submission Date" display. It worked in testing, but during a long stress-test session, my laptop did an NTP sync. The logs then showed submissions appearing to happen before the source code file was last modified, which confused the caching logic. I was essentially betting that system_clock was stable relative to steady_clock over the process lifetime.

    I eventually refactored to exactly what the article suggests: use steady_clock strictly for the runtime enforcement (is duration < 2.0s?), but capture system_clock::now() explicitly at the submission boundary for the logs, rather than trying to do math on the steady timestamp.

    Also, +1 for std::chrono::round in C++20. I’ve seen code where duration_cast was used to "round" execution times to milliseconds for display, but it was silently flooring them. In a competitive programming context, reporting 1000ms when the actual time was 1000.9ms is a misleading difference because the latter gets Time Limit Exceeded error. Explicit rounding makes the intent much clearer.

  • loeg 40 minutes ago
    The thing I ran into most recently is that std::chrono (weirdly?) only supports clocks with compile-time fixed fractional conversion to reference time (~seconds). E.g., you can't implement a std::chrono clock where the count() unit is the native CPU's cycle counter, which will have some runtime-determined conversion to seconds. The types make it impossible.
  • cyberax 22 minutes ago
    C++ chrono is weird. It's both over-abstracted and yet has some thoughtless features that just negate this over-abstraction.

    I remember not being able to represent the time in fractional units, like tertias (1/60-th of a second) but that was mostly an academic problem. More importantly, it was not possible to express duration as a compound object. I wanted to be able to represent the dates with nanosecond precision, but with more than 250 years of range. I think it is still not possible?