Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Browser API's microsecond precision is lost #10

Open
rofferom opened this issue Apr 5, 2024 · 0 comments
Open

Browser API's microsecond precision is lost #10

rofferom opened this issue Apr 5, 2024 · 0 comments

Comments

@rofferom
Copy link

rofferom commented Apr 5, 2024

I'm sharing my analysis about an issue I have encountered. Although I manage to fix my specific usecase, I'd like to have some feedback before trying to open a PR to propose a more global fix.

Context

I wanted to make some performance measurement, and I realized that I had a milliseconds precision.

My test basically relies on this kind of code structure:

let a = Instant::now();

....

let b = Instant::now();
let d = b.duration_since(a).as_micros();
log::info!("{:?} => {:?}: {}", a, b, d.as_micros());

Here is the kind of result is get:

Instant { inner: 1606.7599999904633 } => Instant { inner: 1614.7899999916553 }: 8000

performance.now() theoretical precision

According to https://developer.mozilla.org/en-US/docs/Web/API/Performance/now#performance.now_vs._date.now:

the timestamps returned by performance.now() are not limited to one-millisecond resolution. Instead, they represent times as floating-point numbers with up to microsecond precision

Dirty prototyping

I have patched quickly the library to try to keep the millisecond precision in my specific codepath:

diff --git a/src/std.rs b/src/std.rs
index 7c88189..fee6573 100644
--- a/src/std.rs
+++ b/src/std.rs
@@ -112,9 +112,9 @@ impl Sub<Instant> for Instant {
     type Output = Duration;
 
     fn sub(self, other: Instant) -> Duration {
-        let ms = self.inner - other.inner;
-        assert!(ms >= 0.0);
-        Duration::from_millis(ms as u64)
+        let d = self.inner - other.inner;
+        assert!(d >= 0.0);
+        Duration::from_micros((d * 1000.0) as u64)
     }
 }

Result:

Instant { inner: 2657.5049999952316 } => Instant { inner: 2666.9650000035763 }: 9460
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant