You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

61 lines
1.4 KiB

  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;