Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
sagemathinc
GitHub Repository: sagemathinc/wapython
Path: blob/main/core/wasi-js/src/bindings/browser-hrtime.ts
1067 views
1
/*
2
This is https://github.com/cabinjs/browser-hrtime/blob/master/src/index.ts
3
but modified to not use window, since I want to use this in a WebWorker.
4
Upstream is MIT license.
5
6
This also doesn't define any global variables.
7
*/
8
9
const _perfomancePolyfill = () => {
10
// based on https://gist.github.com/paulirish/5438650 copyright Paul Irish 2015.
11
if (!("performance" in self)) {
12
(self as any).performance = {};
13
}
14
15
Date.now =
16
Date.now ||
17
(() => {
18
// thanks IE8
19
return new Date().getTime();
20
});
21
22
if ("now" in self.performance === false) {
23
let nowOffset = Date.now();
24
25
if (performance.timing && performance.timing.navigationStart) {
26
nowOffset = performance.timing.navigationStart;
27
}
28
29
self.performance.now = () => Date.now() - nowOffset;
30
}
31
};
32
33
const _hrtime = (previousTimestamp?: [number, number]): [number, number] => {
34
_perfomancePolyfill();
35
const baseNow = Math.floor((Date.now() - performance.now()) * 1e-3);
36
const clocktime = performance.now() * 1e-3;
37
let seconds = Math.floor(clocktime) + baseNow;
38
let nanoseconds = Math.floor((clocktime % 1) * 1e9);
39
40
if (previousTimestamp) {
41
seconds = seconds - previousTimestamp[0];
42
nanoseconds = nanoseconds - previousTimestamp[1];
43
if (nanoseconds < 0) {
44
seconds--;
45
nanoseconds += 1e9;
46
}
47
}
48
return [seconds, nanoseconds];
49
};
50
const NS_PER_SEC: number = 1e9;
51
_hrtime.bigint = (time?: [number, number]): bigint => {
52
const diff = _hrtime(time);
53
return (diff[0] * NS_PER_SEC + diff[1]) as unknown as bigint;
54
};
55
export default _hrtime;
56
57