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