Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

The Rust standard library, which provides an API for monotonic timestamps, used to contain this silly hack (with appropriately exasperated comment) because in practice so many platforms and CPUs (Linux, Windows, BSD, x86, x64, Arm) failed to provide monotonicity despite their own documentation: https://github.com/rust-lang/rust/blob/80184183ba0a53aa4f491...


// It seems that this just happens a lot in the wild.

// We're seeing panics across various platforms where consecutive calls

// to `Instant::now`, such as via the `elapsed` function, are panicking

// as they're going backwards. Placed here is a last-ditch effort to try

// to fix things up. We keep a global "latest now" instance which is

// returned instead of what the OS says if the OS goes backwards.

//

// To hopefully mitigate the impact of this, a few platforms are

// excluded as "these at least haven't gone backwards yet".

Why exclude any platforms, just in case they start going backwards for whatever reason?


They say right there, "To hopefully mitigate the impact of this".

Having a mutex right there in the hot path of Instant::now is not great for performance. You expect getting monotonic time to be very fast generally, and some code is written with that assumption (i.e. tracing code measuring spans).


Ah, that's fair. Didn't realize there was a significant performance impact.


Eventually Rust just gave up. Here you go, here's your "monotonically increasing clock" courtesy of your operating system. It might go backwards, try asking your vendor to "fix" that and see if they laugh at you or just ignore you.

Sometimes the OS is broken in a way Rust can fix, for example Rust's current std::sync::RwLock actually does what you wanted on Windows, the C++ std::shared_mutex doesn't. It's documented as working, but it doesn't because the OS is broken and the fix is just on their internal git "next release" branch, not in the Windows you or your customers are running.

But sometimes you're just out of luck. Some minority or older operating systems can't do std::fs::remove_dir_all correctly, so, too bad you get the platform behaviour. It's probably fine, unless it isn't, in which case you should use a real OS.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: