Skip to content

Commit 1ff3100

Browse files
committed
update now implementation to be browser friendly
1 parent f64c1d2 commit 1ff3100

File tree

3 files changed

+39
-19
lines changed

3 files changed

+39
-19
lines changed

packages/target-tools/src/fetchWithTelemetry.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ governing permissions and limitations under the License.
1212
*/
1313
import https from "https";
1414
import http from "http";
15-
import { now } from "./perftool";
15+
import now from "./now";
1616

1717
const PROTOCOL_MAP = {
1818
"http:": http.request,

packages/target-tools/src/now.js

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
/* eslint-disable no-undef */
2+
import { isBrowser, isNodeJS, noop } from "./utils";
3+
import { now as defaultNow } from "./lodash";
4+
5+
const NS_PER_SEC = 1e9;
6+
const MS_PER_NS = 1e6;
7+
8+
let nodeJsNow = noop;
9+
10+
function getNanoSeconds() {
11+
const hr = process.hrtime();
12+
13+
return hr[0] * NS_PER_SEC + hr[1];
14+
}
15+
16+
if (isNodeJS()) {
17+
const upTime = process.uptime() * NS_PER_SEC;
18+
const moduleLoadTime = getNanoSeconds();
19+
const nodeLoadTime = moduleLoadTime - upTime;
20+
21+
// Same nano-precision implementation as performance-now lib
22+
nodeJsNow = function () {
23+
return (getNanoSeconds() - nodeLoadTime) / MS_PER_NS;
24+
};
25+
}
26+
27+
function getNowImpl() {
28+
if (isBrowser()) {
29+
if (window.performance && typeof window.performance.now === "function") {
30+
return window.performance.now.bind(window.performance);
31+
}
32+
return defaultNow;
33+
}
34+
return nodeJsNow;
35+
}
36+
37+
export default getNowImpl();

packages/target-tools/src/perftool.js

Lines changed: 1 addition & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,23 +1,6 @@
11
/* eslint-disable import/prefer-default-export */
22
import { isDefined, isUndefined } from "./utils";
3-
4-
const NS_PER_SEC = 1e9;
5-
const MS_PER_NS = 1e6;
6-
7-
function getNanoSeconds() {
8-
const hr = process.hrtime();
9-
10-
return hr[0] * NS_PER_SEC + hr[1];
11-
}
12-
13-
const UP_TIME = process.uptime() * NS_PER_SEC;
14-
const MODULE_LOAD_TIME = getNanoSeconds();
15-
const NODE_LOAD_TIME = MODULE_LOAD_TIME - UP_TIME;
16-
17-
// Same nano-precision implementation as performance-now lib
18-
export function now() {
19-
return (getNanoSeconds() - NODE_LOAD_TIME) / MS_PER_NS;
20-
}
3+
import now from "./now";
214

225
export function createPerfToolInstance() {
236
let timingIds = {};

0 commit comments

Comments
 (0)