@naturalcycles/bench-lib 4.5.0 → 4.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,5 @@
1
1
  import { _arrayFilled } from '@naturalcycles/js-lib/array/range.js';
2
+ import { formatNumber } from './bench.util.js';
2
3
  import { asciiColor, asciiPlot } from './vendor/asciichart.js';
3
4
  const colors = [
4
5
  asciiColor.blue,
@@ -23,7 +24,7 @@ export function plotAsciiChart(results) {
23
24
  colors,
24
25
  offset: 2,
25
26
  height: 10,
26
- format: y => Math.round(y).toString().padStart(10, ' ') + ' ',
27
+ format: y => formatNumber(y).padStart(15, ' ') + ' ',
27
28
  });
28
29
  s +=
29
30
  '\n' +
@@ -1,10 +1,15 @@
1
- export type BenchFunction = () => void;
1
+ export type BenchFunction = () => any;
2
2
  export interface RunBenchOptions {
3
3
  /**
4
4
  * Functions to benchmark.
5
5
  * Record from function name to a `BenchFunction`.
6
6
  */
7
7
  fns: Record<string, BenchFunction>;
8
+ /**
9
+ * Function name that is considered baseline.
10
+ * If not defined - the first defined function is considered a baseline.
11
+ */
12
+ baseline?: string;
8
13
  /**
9
14
  * How many times to run.
10
15
  * Every second run will be in reverse order.
@@ -7,3 +7,4 @@ export declare function runBenchScript(opt: RunBenchOptions): void;
7
7
  * Only DeferredFunctions are allowed, because of: https://github.com/bestiejs/benchmark.js/issues/111
8
8
  */
9
9
  export declare function runBench(opt: RunBenchOptions): Promise<HertzMap>;
10
+ export declare function formatNumber(n: number): string;
@@ -1,6 +1,6 @@
1
1
  import { _range } from '@naturalcycles/js-lib/array/range.js';
2
2
  import { pDefer } from '@naturalcycles/js-lib/promise/pDefer.js';
3
- import { dimGrey, yellow } from '@naturalcycles/nodejs-lib/colors';
3
+ import { dimGrey, green, grey, red, yellow } from '@naturalcycles/nodejs-lib/colors';
4
4
  import { fs2 } from '@naturalcycles/nodejs-lib/fs2';
5
5
  import { runScript } from '@naturalcycles/nodejs-lib/runScript';
6
6
  import Benchmark from 'benchmark';
@@ -61,17 +61,19 @@ export async function runBench(opt) {
61
61
  if (asciiPlot) {
62
62
  console.log('\n' + plotAsciiChart(avg));
63
63
  }
64
+ printComparisonTable(avg, opt.baseline);
64
65
  return avg;
65
66
  }
66
67
  async function runBenchOnce(opt, run) {
67
68
  const defer = pDefer();
68
69
  const suite = new Benchmark.Suite()
69
70
  .on('cycle', (event) => {
70
- // eslint-disable-next-line @typescript-eslint/no-base-to-string
71
+ // oxlint-disable-next-line @typescript-eslint/no-base-to-string
71
72
  console.log(String(event.target));
72
73
  // console.log(event.target)
73
74
  })
74
75
  .on('complete', function () {
76
+ // oxlint-disable-next-line typescript/restrict-plus-operands
75
77
  console.log(`Fastest in run ${yellow(run)} is ` + this.filter('fastest').map('name'));
76
78
  // console.log(this[0].stats)
77
79
  // console.log(this)
@@ -99,6 +101,58 @@ async function runBenchOnce(opt, run) {
99
101
  });
100
102
  return await defer;
101
103
  }
104
+ function printComparisonTable(avg, baselineName) {
105
+ const names = Object.keys(avg);
106
+ if (names.length < 2)
107
+ return;
108
+ const baseline = baselineName ?? names[0];
109
+ const baselineHz = avg[baseline];
110
+ if (!baselineHz) {
111
+ console.log(red(`baseline "${baseline}" not found in results`));
112
+ return;
113
+ }
114
+ // Calculate column widths
115
+ const maxNameLen = Math.max(...names.map(n => n.length));
116
+ const maxHzLen = Math.max(...Object.values(avg).map(hz => formatNumber(hz).length));
117
+ const maxTimeLen = Math.max(...Object.values(avg).map(hz => formatTime(hz).length));
118
+ // Header
119
+ console.log(`\n${grey('+ faster / - slower, ops/sec')}\n`);
120
+ console.log(` ${'name'.padEnd(maxNameLen)} ${'time'.padStart(maxTimeLen)} ${'ops/sec'.padStart(maxHzLen)} diff`);
121
+ console.log(` ${grey('─'.repeat(maxNameLen + maxHzLen + maxTimeLen + 14))}`);
122
+ for (const name of names) {
123
+ const hz = avg[name];
124
+ const paddedName = name.padEnd(maxNameLen);
125
+ const hzStr = formatNumber(hz).padStart(maxHzLen);
126
+ const timeStr = formatTime(hz).padStart(maxTimeLen);
127
+ if (name === baseline) {
128
+ console.log(` ${paddedName} ${timeStr} ${hzStr} ${grey('baseline')}`);
129
+ continue;
130
+ }
131
+ // Positive = more ops/sec = faster, Negative = less ops/sec = slower
132
+ const diff = ((hz - baselineHz) / baselineHz) * 100;
133
+ const sign = diff > 0 ? '+' : '';
134
+ const diffStr = `${sign}${diff.toFixed(1)}%`;
135
+ const colorFn = diff >= 0 ? green : red;
136
+ console.log(` ${paddedName} ${timeStr} ${hzStr} ${colorFn(diffStr)}`);
137
+ }
138
+ console.log();
139
+ }
140
+ export function formatNumber(n) {
141
+ return Math.round(n).toLocaleString('en-US');
142
+ }
143
+ function formatTime(hz) {
144
+ const seconds = 1 / hz;
145
+ if (seconds >= 1)
146
+ return `${seconds.toFixed(2)} s`;
147
+ const ms = seconds * 1000;
148
+ if (ms >= 1)
149
+ return `${ms.toFixed(2)} ms`;
150
+ const us = ms * 1000;
151
+ if (us >= 1)
152
+ return `${us.toFixed(2)} µs`;
153
+ const ns = us * 1000;
154
+ return `${ns.toFixed(2)} ns`;
155
+ }
102
156
  /*
103
157
  function benchResultsToVegaSpec(map: HertzMap): Spec {
104
158
  const values = Object.entries(map).map(([name, hz]) => {
@@ -7,7 +7,7 @@ Adapted for typescript.
7
7
 
8
8
  Super-experimental!
9
9
  */
10
- /* eslint-disable */
10
+ // oxlint-disable no-new-array -- vendored ASCII chart relies on Array constructors
11
11
  export const asciiColor = {
12
12
  black: '\u001B[30m',
13
13
  red: '\u001B[31m',
package/package.json CHANGED
@@ -13,12 +13,12 @@
13
13
  "@types/benchmark": "^2",
14
14
  "@types/cors": "^2",
15
15
  "@types/express": "^5",
16
- "@types/node": "^24",
16
+ "@types/node": "^25",
17
17
  "express": "^5",
18
18
  "fastify": "^5",
19
19
  "helmet": "^8",
20
20
  "nanoid": "^5",
21
- "@naturalcycles/dev-lib": "19.11.0"
21
+ "@naturalcycles/dev-lib": "20.20.0"
22
22
  },
23
23
  "exports": {
24
24
  ".": "./dist/index.js"
@@ -37,9 +37,9 @@
37
37
  "directory": "packages/bench-lib"
38
38
  },
39
39
  "engines": {
40
- "node": ">=22.12.0"
40
+ "node": ">=24.10.0"
41
41
  },
42
- "version": "4.5.0",
42
+ "version": "4.6.0",
43
43
  "description": "Benchmarking library, based on Benchmark.js and Autocannon",
44
44
  "author": "Natural Cycles Team",
45
45
  "license": "MIT",