clock-is-accurate.js 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. "use strict";
  2. const { hrtime } = require("./utils");
  3. // The HR-TIME spec calls for 5-μs accuracy. Check that we have that in both hrtime() and Date.now().
  4. function testClockAccuracy() {
  5. // Test hrtime() first. The check is simpler and more stable, and we use hrtime() to measure Date.now()'s performance.
  6. const roundTrip = hrtime(hrtime());
  7. if (roundTrip[0] > 1 || roundTrip[1] > 5e3 * 2) {
  8. return false;
  9. }
  10. // Test Date.now() twice: first with a looser bound (10 μs) but with a smaller run time to filter out very bad
  11. // Date.now() performance, and then with a tighter bound (5 μs) to check we have the accuracy we need.
  12. let times;
  13. // eslint-disable-next-line no-unused-vars
  14. let cur;
  15. let start;
  16. let end;
  17. times = 100;
  18. start = hrtime();
  19. while (times-- > 0) {
  20. cur = Date.now();
  21. }
  22. end = hrtime(start);
  23. if ((end[0] * 1e9 + end[1]) > 1000000) {
  24. return false;
  25. }
  26. times = 10000;
  27. start = hrtime();
  28. while (times-- > 0) {
  29. cur = Date.now();
  30. }
  31. end = hrtime(start);
  32. if ((end[0] * 1e9 + end[1]) > 50000000) {
  33. return false;
  34. }
  35. return true;
  36. }
  37. // Warm up the function.
  38. testClockAccuracy();
  39. testClockAccuracy();
  40. testClockAccuracy();
  41. const TIMES = 5;
  42. const THRESHOLD = 0.6 * TIMES;
  43. let accurates = 0;
  44. for (let i = 0; i < TIMES; i++) {
  45. if (testClockAccuracy()) {
  46. accurates++;
  47. }
  48. }
  49. const isAccurate = accurates >= THRESHOLD;
  50. module.exports = isAccurate;