performance.js 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. "use strict";
  2. // Actual implementation of the Performance class.
  3. const clockIsAccurate = require("./clock-is-accurate");
  4. const calculateClockOffset = require("./calculate-clock-offset");
  5. const { hrtime, toMS } = require("./utils");
  6. const kTimeOrigin = Symbol("time origin");
  7. const kTimeOriginTimestamp = Symbol("time origin timestamp");
  8. class Performance {
  9. constructor() {
  10. // Time origin.
  11. const timeOrigin = hrtime();
  12. this[kTimeOrigin] = timeOrigin;
  13. if (clockIsAccurate) {
  14. // Let |t1| be the DOMHighResTimeStamp representing the high resolution Unix time at which the global monotonic
  15. // clock is zero. This has to be calculated for every Performance object to account for clock drifts.
  16. const t1 = calculateClockOffset();
  17. // Let |t2| be the DOMHighResTimeStamp representing the high resolution time value of the global monotonic clock
  18. // at global's time origin.
  19. const t2 = toMS(timeOrigin);
  20. // Return the sum of |t1| and |t2|.
  21. this[kTimeOriginTimestamp] = t1 + t2;
  22. } else {
  23. // Clock isn't accurate enough. Use millisecond accuracy per spec.
  24. const cur = Date.now();
  25. this[kTimeOriginTimestamp] = cur;
  26. }
  27. }
  28. // The timeOrigin getter actually returns the time origin timestamp, not the raw time origin.
  29. get timeOrigin() {
  30. return this[kTimeOriginTimestamp];
  31. }
  32. now() {
  33. const diff = toMS(hrtime(this[kTimeOrigin]));
  34. return clockIsAccurate ? diff : Math.round(diff);
  35. }
  36. toJSON() {
  37. return {
  38. timeOrigin: this.timeOrigin
  39. };
  40. }
  41. }
  42. module.exports = { Performance };