forked from rocicorp/mono
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtimed.ts
More file actions
29 lines (27 loc) · 830 Bytes
/
timed.ts
File metadata and controls
29 lines (27 loc) · 830 Bytes
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
type LogFunction = ((...args: unknown[]) => void) | undefined;
declare const performance: {
now(): number;
};
/**
* Times some async function and writes the result to a provided log function.
* The log function can be undefined to simplify use with OptionalLogger.
* @param log Log function to write to (ie LogContext.log)
* @param label Label to write at start and end of function
* @param fn Function to time
* @returns The result of fn
*/
export async function timed<R>(
log: LogFunction | undefined,
label: string,
fn: () => Promise<R>,
): Promise<R> {
log?.(`Starting ${label}`);
const clock = typeof performance !== 'undefined' ? performance : Date;
const t0 = clock.now();
try {
return await fn();
} finally {
const t1 = clock.now();
log?.(`Finished ${label} in ${t1 - t0}ms`);
}
}