示例基准
🌐 Example benchmark
把以下内容保存为 benchmark.mjs:
🌐 Save the following as benchmark.mjs:
import { bench, suite } from 'node:bench';
suite('URL', () => {
const input = 'https://example.com/a?b=c';
bench('construct', {
samples: 30,
params: { input: 'short' },
}, (b) => {
const operations = 10_000;
let totalLength = 0;
b.start();
for (let i = 0; i < operations; i++) {
totalLength += new URL(input).href.length;
}
b.end(operations);
if (totalLength !== operations * input.length) {
throw new Error('Unexpected URL result');
}
});
}); 从命令行运行基准测试:
🌐 Run the benchmark from the command line:
node --experimental-bench --bench benchmark.mjs 基准测试会按照声明的顺序依次执行。声明的基准测试会自动安排。可以在声明的同一轮中调用 run() 来使用事件流或设置过滤。如果自动安排的运行失败且没有调用 run(),进程的退出代码会被设置为 1。
🌐 Benchmarks are executed serially in declaration order. Declared benchmarks are
scheduled automatically. Call run() during the same turn as the declarations
to consume the event stream or configure filtering.
If an automatically scheduled run fails and run() was not called, the process
exit code is set to 1.