Skip to content

Commit 017697d

Browse files
committed
Refactor Timing and TimingCollector classes; update README for improved usage instructions
1 parent 1a256c8 commit 017697d

File tree

3 files changed

+14
-16
lines changed

3 files changed

+14
-16
lines changed

README.md

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -44,13 +44,13 @@ You can also manually collect timings:
4444
```ts
4545
import { Timing } from "@edgefirst-dev/server-timing";
4646

47+
// measures are taken from the time this is created
4748
let timing = new Timing("name", "description");
4849

49-
timing.measure(async () => {
50-
// do something
51-
});
50+
await doSomething(); // do something
5251

53-
collector.add(timing);
52+
timing.end(); // end the measurement
53+
collector.add(timing); // add the timing to the collector
5454
```
5555

5656
Each `Timing` can be used once. If you want to take different measurements, create a new `Timing` instance.

src/lib/timing-collector.ts

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,10 @@ export class TimingCollector {
3636
typeof descriptionOrFn === "string" ? descriptionOrFn : undefined,
3737
);
3838

39-
return timing.measure(callback).finally(() => void this.collect(timing));
39+
return callback().finally(() => {
40+
timing.end();
41+
this.collect(timing);
42+
});
4043
}
4144

4245
/**

src/lib/timing.ts

Lines changed: 6 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,26 +1,21 @@
11
export class Timing implements PerformanceServerTiming {
2-
start = 0;
3-
end = 0;
2+
readonly #start = performance.now();
3+
#end = 0;
44

55
constructor(
66
public name: string,
77
public description = "",
88
) {}
99

1010
get duration() {
11-
if (this.end === 0) return 0;
12-
let result = this.end - this.start;
11+
if (this.#end === 0) return 0;
12+
let result = this.#end - this.#start;
1313
if (result < 0) return 0;
1414
return result;
1515
}
1616

17-
async measure<T>(fn: Timing.MeasureFunction<T>): Promise<T> {
18-
this.start = performance.now();
19-
try {
20-
return await fn();
21-
} finally {
22-
this.end = performance.now();
23-
}
17+
end() {
18+
this.#end = performance.now();
2419
}
2520

2621
toString() {

0 commit comments

Comments
 (0)