-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathtime.ts
49 lines (40 loc) · 1.14 KB
/
time.ts
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
let labelToTime = new Map<string, number>();
let labelToStartTime = new Map<string, number>();
export async function time(
label: string,
promiseOrFunction: Promise<any> | (() => Promise<any>) | (() => any),
) {
let now = performance.now();
let result;
try {
if (typeof promiseOrFunction === 'function') {
result = await promiseOrFunction();
} else {
result = await promiseOrFunction;
}
} finally {
let diff = performance.now() - now;
let lastTime = labelToTime.get(label) || 0;
labelToTime.set(label, lastTime + diff);
return result;
}
}
export async function timeStart(label: string) {
labelToStartTime.set(label, performance.now());
}
export async function timeEnd(label: string) {
let now = performance.now();
let startTime = labelToStartTime.get(label);
if (startTime === undefined) {
console.error(`No start time found for label ${label}`);
return NaN;
}
let diff = now - startTime;
let lastTime = labelToTime.get(label) || 0;
labelToTime.set(label, lastTime + diff);
labelToStartTime.delete(label);
return diff;
}
export function getTimes() {
return labelToTime;
}