std::time::Instant, UNIX_EPOCH?

EDIT: needs to work on wasm32

On that page, we have:

struct Instant
struct SystemTime
const UNIX_EPOCH: SystemTime

Is there a way to get UNIX_EPOCH as an Instant ?

XY problem: I want a monotonic clock in milliseconds.

How about calling Instant::now() at program startup and using that as the epoch?

1 Like
  1. This works.

  2. I'll probably end up doing this.

  3. If possible, given I'm lazy, I'd prefer to not go through the API change of threading this state through everything.

No, Instant explicitly avoids connection to any particular epoch. WASI uses the monotonic clockid:

The store-wide monotonic clock, which is defined as a clock measuring real time, whose value cannot be adjusted and which cannot have negative clock jumps. The epoch of this clock is undefined. The absolute time value of this clock therefore has no meaning.

2 Likes

Negative result useful too. Thanks for explaining why it can't exist.

In principle you could "compute the epoch" by doing Instant::now() - (SystemTime::now() - std::time::UNIX_EPOCH), but since the system time is not monotonic, this value may drift away from the unix epoch over time. It may also jump far away from the epoch when the computer is suspended or when the system time is directly modified.

Eh, I just took your first suggestion and modified the API. Turns out an easy operation with a static type system.

1 Like

Note that this applies to wasm32-wasi which requires the host to provide a POSIX-like set of functions, one of which gives you time.

The wasm32-unknown-unknown target knows nothing about its environment, including whether browser APIs are available, so you won't get meaningful results from things in std like Instant::now() which require external information. I'm guessing all time calcs with Instant will say zero seconds has passed and you'll have to use Date.now() from JavaScript.

Edit: found the source code - Instant::now() panics unconditionally.

True. I forgot to mention I was using https://crates.io/crates/instant

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.