diff --git a/src/utils.ts b/src/utils.ts index b05b299..9eadf1a 100644 --- a/src/utils.ts +++ b/src/utils.ts @@ -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. diff --git a/test/index.test.ts b/test/index.test.ts index 7d066cf..7119e37 100644 --- a/test/index.test.ts +++ b/test/index.test.ts @@ -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 () => { @@ -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 () => {