How to create instance-able custom clock with epoch set at runtime

Viewed 63

My question is similar to this one (How to create a custom clock for use in std::chrono functions?) but with two minor differences:

  1. The epoch isn't known until runtime
  2. There could potentially be multiple instances of the clock, each with their own epoch

The use case I'm thinking of is for video stream time. i.e. each frame in a video stream has a timestamp (pts, presentation time stamp) relative to the timestamp of the first frame. There could be multiple video streams, each with their own stream start time.

I think the epoch not being known until runtime is easy enough, just add a set_epoch function. however I'm not sure how it would be instanced where the now() function is static (which I would assume would require set_epoch to be static.)

So far I've just handled this by making the timestamp a duration instead of a time_point but that seems to be kind of an abuse of the types. It also Is that the best solution or is there a better way? I guess maybe a broader question is, is it better to use a time_point or a duration type for a timestamp? A time_point seems the natural fit, but that means you'd have to truck around the clock definition. A duration doesn't seem to fit the intended definition, but decouples it from the clock definition.

1 Answers

Ultimately I think you're saying: I need a stateful chrono::clock. Right?

The epoch has to be a run-time data member of the clock. And that doesn't really meet the Cpp17Clock requirements.

It turns out that the C++20 type std::chrono::local_t is also a clock that doesn't meet the Cpp17Clock requirements:

// [time.clock.local], local time
struct local_t {};

Convenience link: http://eel.is/c++draft/time.clock.local

The family of time points denoted by local_­time<Duration> are based on the pseudo clock local_­t. local_­t has no member now() and thus does not meet the clock requirements.

P2212 was written to address clocks that don't meet the Cpp17Clock requirements. It turns out that one can create time_points based on such clocks without any problem. The only thing you can't do with such clocks is call algorithms that require the Cpp17Clock requirements. For example std::this_thread::sleep_until.

But if you don't want to call sleep_until with a MyCuriousClock::time_point, then no harm, no foul. If the standard can create a clock (std::chrono::local_t) that doesn't meet the Cpp17Clock requirements, then so can you — as long as you understand its limitations.

Related