generated from ryanatkn/fuz_template
-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
timings.ts
78 lines (66 loc) 路 1.97 KB
/
timings.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
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
77
78
import {round} from './maths.js';
export interface Stopwatch {
(reset?: boolean): number;
}
/**
* Tracks elapsed time in milliseconds.
*/
export const create_stopwatch = (decimals = 2): Stopwatch => {
let start = performance.now();
return (reset = false) => {
const end = performance.now();
const elapsed = round(Number(end - start), decimals);
if (reset) start = end;
return elapsed;
};
};
export type Timings_Key = string | number;
export class Timings {
private readonly timings = new Map<Timings_Key, number>();
private readonly stopwatches = new Map<Timings_Key, Stopwatch>();
constructor(public readonly decimals?: number) {}
start(key: Timings_Key, decimals = this.decimals): () => number {
const final_key = this.next_key(key);
this.stopwatches.set(final_key, create_stopwatch(decimals));
this.timings.set(final_key, undefined!); // initializing to preserve order
return () => this.stop(final_key);
}
private next_key(key: Timings_Key): Timings_Key {
if (!this.stopwatches.has(key)) return key;
let i = 2;
while (true) {
const next = key + '_' + i++;
if (!this.stopwatches.has(next)) return next;
}
}
private stop(key: Timings_Key): number {
const stopwatch = this.stopwatches.get(key);
if (!stopwatch) return 0; // TODO maybe warn?
this.stopwatches.delete(key);
const timing = stopwatch();
this.timings.set(key, timing);
return timing;
}
get(key: Timings_Key): number {
const timing = this.timings.get(key);
if (timing === undefined) return 0; // TODO maybe warn?
return timing;
}
entries(): IterableIterator<[Timings_Key, number]> {
return this.timings.entries();
}
/**
* Merges other timings into this one,
* adding together values with identical keys.
*/
merge(timings: Timings): void {
for (const [key, timing] of timings.entries()) {
this.timings.set(key, (this.timings.get(key) || 0) + timing);
}
}
// clear(): void {
// this.stopwatches.clear();
// this.timings.clear();
// }
// toJSON() {} ?????
}