Skip to content Skip to sidebar Skip to footer

How To Get Microsecond Timings In Javascript Since Spectre And Meltdown

The situation When writing high-performance JavaScript code, the standard profiling tools offered by Chrome et al are not always sufficient. They only seem to offer function-level

Solution 1:

Firefox does have a config setting called privacy.reduceTimerPrecision that disables the Spectre mitigation. You can switch it to false using Firefox's about:config page (type about:config into the address bar).

Figured this out via a hint on MDN.

Solution 2:

Since Firefox 79, you can use high resolution timers if you make your server send two headers with your page:

Starting with Firefox 79, high resolution timers can be used if you cross-origin isolate your document using the Cross-Origin-Opener-Policy and Cross-Origin-Embedder-Policy headers:

Cross-Origin-Opener-Policy: same-originCross-Origin-Embedder-Policy: require-corp

These headers ensure a top-level document does not share a browsing context group with cross-origin documents. COOP process-isolates your document and potential attackers can't access to your global object if they were opening it in a popup, preventing a set of cross-origin attacks dubbed XS-Leaks.

Ref: https://developer.mozilla.org/en-US/docs/Web/API/Performance/now

It's not mentioned on that page as of this moment, but with a little experiment, I've concluded that the accuracy of the timer is 20µs with those headers present, which is 50x better than the accuracy you get by default.

(() => {
  const start = performance.now();
  let diff;
  while ((diff = performance.now() - start) === 0);
  return diff;
})();

This returns 0.02 or a value very close to 0.02 with those headers, and 1 without.

Post a Comment for "How To Get Microsecond Timings In Javascript Since Spectre And Meltdown"