Skip to content

Commit d9a238a

Browse files
perf: bind timestamping function to their modules (#149)
Signed-off-by: Jérôme Benoit <jerome.benoit@piment-noir.org>
1 parent 22b54f0 commit d9a238a

File tree

2 files changed

+41
-4
lines changed

2 files changed

+41
-4
lines changed

src/utils.ts

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,9 +3,11 @@ import type { Fn, Statistics } from './types';
33

44
export const nanoToMs = (nano: number) => nano / 1e6;
55

6-
export const hrtimeNow = () => nanoToMs(Number(process.hrtime.bigint()));
6+
const hrtimeBigint = process.hrtime.bigint.bind(process.hrtime);
7+
export const hrtimeNow = () => nanoToMs(Number(hrtimeBigint()));
78

8-
export const now = () => performance.now();
9+
const performanceNow = performance.now.bind(performance);
10+
export const now = performanceNow;
911

1012
/**
1113
* Checks if a value is a promise-like object.

test/index.test.ts

Lines changed: 37 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import { expect, test, vi } from 'vitest';
2-
import { Bench, type Task } from '../src';
2+
import { Bench, type Task, hrtimeNow } from '../src';
33

4-
test('basic', async () => {
4+
test('now() basic', async () => {
55
const bench = new Bench({ time: 100 });
66
bench
77
.add('foo', async () => {
@@ -36,6 +36,41 @@ test('basic', async () => {
3636
).toBeCloseTo(1000, 1);
3737
});
3838

39+
test('hrtimeNow() basic', async () => {
40+
const bench = new Bench({ time: 100, now: hrtimeNow });
41+
bench
42+
.add('foo', async () => {
43+
await new Promise((resolve) => setTimeout(resolve, 50));
44+
})
45+
.add('bar', async () => {
46+
await new Promise((resolve) => setTimeout(resolve, 100));
47+
});
48+
49+
await bench.run();
50+
51+
const { tasks } = bench;
52+
53+
expect(tasks.length).toEqual(2);
54+
55+
expect(tasks[0]?.name).toEqual('foo');
56+
expect(tasks[0]?.result?.totalTime).toBeGreaterThan(50);
57+
expect(tasks[0]?.result?.latency.mean).toBeGreaterThan(50);
58+
// throughput mean is ops/s, period is ms unit value
59+
expect(
60+
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
61+
tasks[0]!.result!.throughput.mean * tasks[0]!.result!.period,
62+
).toBeCloseTo(1000, 1);
63+
64+
expect(tasks[1]?.name).toEqual('bar');
65+
expect(tasks[1]?.result?.totalTime).toBeGreaterThan(100);
66+
expect(tasks[1]?.result?.latency.mean).toBeGreaterThan(100);
67+
// throughput mean is ops/s, period is ms unit value
68+
expect(
69+
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
70+
tasks[1]!.result!.throughput.mean * tasks[1]!.result!.period,
71+
).toBeCloseTo(1000, 1);
72+
});
73+
3974
test('bench and task runs, time consistency', async () => {
4075
const bench = new Bench({ time: 100, iterations: 15 });
4176
bench.add('foo', async () => {

0 commit comments

Comments
 (0)