Skip to content

Commit

Permalink
perf: bind timestamping function to their modules (#149)
Browse files Browse the repository at this point in the history
Signed-off-by: Jérôme Benoit <jerome.benoit@piment-noir.org>
  • Loading branch information
jerome-benoit authored Oct 20, 2024
1 parent 22b54f0 commit d9a238a
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 4 deletions.
6 changes: 4 additions & 2 deletions src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,11 @@ import type { Fn, Statistics } from './types';

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

export const hrtimeNow = () => nanoToMs(Number(process.hrtime.bigint()));
const hrtimeBigint = process.hrtime.bigint.bind(process.hrtime);
export const hrtimeNow = () => nanoToMs(Number(hrtimeBigint()));

export const now = () => performance.now();
const performanceNow = performance.now.bind(performance);
export const now = performanceNow;

/**
* Checks if a value is a promise-like object.
Expand Down
39 changes: 37 additions & 2 deletions test/index.test.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { expect, test, vi } from 'vitest';
import { Bench, type Task } from '../src';
import { Bench, type Task, hrtimeNow } from '../src';

test('basic', async () => {
test('now() basic', async () => {
const bench = new Bench({ time: 100 });
bench
.add('foo', async () => {
Expand Down Expand Up @@ -36,6 +36,41 @@ test('basic', async () => {
).toBeCloseTo(1000, 1);
});

test('hrtimeNow() basic', async () => {
const bench = new Bench({ time: 100, now: hrtimeNow });
bench
.add('foo', async () => {
await new Promise((resolve) => setTimeout(resolve, 50));
})
.add('bar', async () => {
await new Promise((resolve) => setTimeout(resolve, 100));
});

await bench.run();

const { tasks } = bench;

expect(tasks.length).toEqual(2);

expect(tasks[0]?.name).toEqual('foo');
expect(tasks[0]?.result?.totalTime).toBeGreaterThan(50);
expect(tasks[0]?.result?.latency.mean).toBeGreaterThan(50);
// throughput mean is ops/s, period is ms unit value
expect(
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
tasks[0]!.result!.throughput.mean * tasks[0]!.result!.period,
).toBeCloseTo(1000, 1);

expect(tasks[1]?.name).toEqual('bar');
expect(tasks[1]?.result?.totalTime).toBeGreaterThan(100);
expect(tasks[1]?.result?.latency.mean).toBeGreaterThan(100);
// throughput mean is ops/s, period is ms unit value
expect(
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
tasks[1]!.result!.throughput.mean * tasks[1]!.result!.period,
).toBeCloseTo(1000, 1);
});

test('bench and task runs, time consistency', async () => {
const bench = new Bench({ time: 100, iterations: 15 });
bench.add('foo', async () => {
Expand Down

0 comments on commit d9a238a

Please sign in to comment.