-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathclock-epoch.ts
More file actions
76 lines (62 loc) · 1.76 KB
/
clock-epoch.ts
File metadata and controls
76 lines (62 loc) · 1.76 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
import process from 'node:process';
import { threadId } from 'node:worker_threads';
export type Microseconds = number;
export type Milliseconds = number;
const msToUs = (ms: number): Microseconds => Math.round(ms * 1000);
const usToUs = (us: number): Microseconds => Math.round(us);
/**
* Defines clock utilities for time conversions.
* Handles time origins in NodeJS and the Browser
* Provides process and thread IDs.
* @param init
*/
export type EpochClockOptions = {
pid?: number;
tid?: number;
};
/**
* Creates epoch-based clock utility.
* Epoch time has been the time since January 1, 1970 (UNIX epoch).
* Date.now gives epoch time in milliseconds.
* performance.now() + performance.timeOrigin when available is used for higher precision.
*/
export function epochClock(init: EpochClockOptions = {}) {
const pid = init.pid ?? process.pid;
const tid = init.tid ?? threadId;
const timeOriginMs = performance.timeOrigin;
const epochNowUs = (): Microseconds =>
msToUs(timeOriginMs + performance.now());
const fromEpochUs = usToUs;
const fromEpochMs = msToUs;
const fromPerfMs = (perfMs: Milliseconds): Microseconds =>
msToUs(timeOriginMs + perfMs);
const fromEntryStartTimeMs = fromPerfMs;
const fromEntry = (
entry: {
startTime: Milliseconds;
entryType: string;
duration: Milliseconds;
},
useEndTime = false,
) =>
fromPerfMs(
entry.startTime +
(entry.entryType === 'measure' && useEndTime ? entry.duration : 0),
);
const fromDateNowMs = fromEpochMs;
return {
timeOriginMs,
pid,
tid,
epochNowUs,
msToUs,
usToUs,
fromEpochMs,
fromEpochUs,
fromPerfMs,
fromEntry,
fromEntryStartTimeMs,
fromDateNowMs,
};
}
export const defaultClock = epochClock();