|
5 | 5 | [](https://discord.gg/c3UUYNcHrU) |
6 | 6 | [](https://github.com/neostandard/neostandard) |
7 | 7 |
|
8 | | -Benchmark your code easily with Tinybench, a simple, tiny and light-weight `10KB` (`2KB` minified and gzipped) benchmarking library! |
| 8 | +A simple, tiny and lightweight benchmarking library! |
9 | 9 | You can run your benchmarks in multiple JavaScript runtimes, Tinybench is completely based on the Web APIs with proper timing using |
10 | 10 | `process.hrtime` or `performance.now`. |
11 | 11 |
|
@@ -87,12 +87,12 @@ Both the `Task` and `Bench` classes extend the `EventTarget` object. So you can |
87 | 87 | ```js |
88 | 88 | // runs on each benchmark task's cycle |
89 | 89 | bench.addEventListener('cycle', (evt) => { |
90 | | - const task = evt.task!; |
| 90 | + const task = evt.task; |
91 | 91 | }); |
92 | 92 |
|
93 | 93 | // runs when timer saturation is detected for a task's measured samples |
94 | 94 | bench.addEventListener('warning', (evt) => { |
95 | | - const task = evt.task!; |
| 95 | + const task = evt.task; |
96 | 96 | const reason = evt.reason; // 'zero-dominated' | 'low-distinct' | 'zero-mad' |
97 | 97 | }); |
98 | 98 | ``` |
@@ -102,7 +102,7 @@ bench.addEventListener('warning', (evt) => { |
102 | 102 | ```js |
103 | 103 | // runs only on this benchmark task's cycle |
104 | 104 | task.addEventListener('cycle', (evt) => { |
105 | | - const task = evt.task!; |
| 105 | + const task = evt.task; |
106 | 106 | }); |
107 | 107 | ``` |
108 | 108 |
|
@@ -117,7 +117,8 @@ checking if provided function is an `AsyncFunction` or if it returns a |
117 | 117 | You can also explicitly set the `async` option to `true` or `false` when adding |
118 | 118 | a task, thus avoiding the detection. Set `async: false` only for a genuinely |
119 | 119 | synchronous task; to measure the synchronous cost of a function that returns a |
120 | | -`Promise`, record it via `overriddenDuration` instead. |
| 120 | +`Promise`, record it via `overriddenDuration` instead (see |
| 121 | +[Task-Supplied Measurements](#task-supplied-measurements)). |
121 | 122 |
|
122 | 123 | ```ts |
123 | 124 | const bench = new Bench() |
@@ -146,11 +147,21 @@ await bench.run() |
146 | 147 | ```ts |
147 | 148 | const bench = new Bench({ |
148 | 149 | concurrency: 'task', // The concurrency mode to determine how tasks are run. |
149 | | - threshold: 10, // The maximum number of concurrent tasks to run. Defaults to Number.POSITIVE_INFINITY. |
| 150 | + threshold: 10, // Maximum concurrent iterations within a task. Defaults to Infinity. |
150 | 151 | }) |
151 | 152 | await bench.run() |
152 | 153 | ``` |
153 | 154 |
|
| 155 | +With `concurrency: null` or `'bench'`, each task runs until both its time |
| 156 | +budget and minimum iteration count are met. With `concurrency: 'task'`, |
| 157 | +iterations stop being scheduled when either positive limit is reached; |
| 158 | +`threshold` limits concurrent iterations within that task, not concurrent |
| 159 | +benchmark tasks. Disabling the iteration limit with `iterations: 0` requires |
| 160 | +a finite `threshold` (for example, `threshold: 10`), not the default |
| 161 | +`Infinity`. These rules also apply to `warmupTime` and `warmupIterations` |
| 162 | +in `warmup()`. `Task.warmupSync()` always uses the sequential rules, regardless |
| 163 | +of the configured concurrency. |
| 164 | + |
154 | 165 | ## Convert task results for `console.table()` |
155 | 166 |
|
156 | 167 | You can convert the benchmark results to a table format suitable for |
@@ -259,13 +270,13 @@ If you want to provide a custom timestamp provider, you can create an object tha |
259 | 270 | the `TimestampProvider` interface: |
260 | 271 |
|
261 | 272 | ```ts |
262 | | -import { Bench, TimestampProvider } from 'tinybench' |
| 273 | +import { Bench, type TimestampProvider } from 'tinybench' |
263 | 274 |
|
264 | 275 | // Custom timestamp provider using Date.now() |
265 | 276 | const dateNowTimestampProvider: TimestampProvider = { |
266 | 277 | name: 'dateNow', // name of the provider |
267 | 278 | fn: Date.now, // function that returns the current timestamp |
268 | | - toMs: ts => ts, // convert the timestamp to milliseconds |
| 279 | + toMs: ts => Number(ts), // convert the timestamp to milliseconds |
269 | 280 | fromMs: ts => ts, // convert milliseconds to the format used by fn() |
270 | 281 | } |
271 | 282 |
|
@@ -337,7 +348,9 @@ const overhead = calibrateTimerOverhead(hrtimeNowTimestampProvider, { |
337 | 348 | sub-microsecond samples stay over-measured even with `subtractTimerOverhead`. |
338 | 349 | Use `overriddenDuration` for such sub-resolution work. |
339 | 350 |
|
340 | | -## Per-Sample Override (`overriddenDuration`) |
| 351 | +## Task-Supplied Measurements |
| 352 | + |
| 353 | +### Per-sample duration (`overriddenDuration`) |
341 | 354 |
|
342 | 355 | A task function may return an object containing `overriddenDuration` |
343 | 356 | (in ms). That value is recorded in place of the timer-measured sample: |
@@ -347,7 +360,9 @@ value. Useful for externally-timed work or sub-overhead measurements |
347 | 360 | that the timer cannot resolve. |
348 | 361 |
|
349 | 362 | ```ts |
350 | | -bench.add('externally-timed', () => { |
| 363 | +import type { FnReturnedObject } from 'tinybench' |
| 364 | + |
| 365 | +bench.add('externally-timed', (): FnReturnedObject => { |
351 | 366 | const start = process.hrtime.bigint() |
352 | 367 | doWork() |
353 | 368 | const elapsedMs = Number(process.hrtime.bigint() - start) / 1e6 |
@@ -358,22 +373,79 @@ bench.add('externally-timed', () => { |
358 | 373 | Overridden samples are excluded from `Task.detectedResolution` and |
359 | 374 | from timer-saturation detection. |
360 | 375 |
|
| 376 | +### Iteration cost (`overriddenIterationCost`) |
| 377 | + |
| 378 | +When one iteration batches several inner calls, the per-call value you |
| 379 | +want in the statistics differs from what the iteration actually costs |
| 380 | +the `time` / `warmupTime` budget. Return `overriddenIterationCost` |
| 381 | +(in ms) to declare the whole iteration's wall-clock cost: |
| 382 | + |
| 383 | +```ts |
| 384 | +import type { FnReturnedObject } from 'tinybench' |
| 385 | + |
| 386 | +bench.add('batched', () => { |
| 387 | + const innerCalls = 100 |
| 388 | + const start = process.hrtime.bigint() |
| 389 | + for (let i = 0; i < innerCalls; i++) parse(input) |
| 390 | + const elapsedMs = Number(process.hrtime.bigint() - start) / 1e6 |
| 391 | + return { |
| 392 | + overriddenDuration: elapsedMs / innerCalls, // mean per call in this batch |
| 393 | + overriddenIterationCost: elapsedMs, // budget cost of the iteration |
| 394 | + } satisfies FnReturnedObject |
| 395 | +}) |
| 396 | +``` |
| 397 | + |
| 398 | +Each sample is the mean duration per call in one batch. Percentiles and |
| 399 | +dispersion describe these batch means, not the individual calls within a batch. |
| 400 | + |
| 401 | +Semantics: |
| 402 | + |
| 403 | +- The sample uses a valid `overriddenDuration`, otherwise the timer-measured |
| 404 | + duration. The sequential budget uses a valid `overriddenIterationCost`, |
| 405 | + otherwise the sample before timer-overhead correction. Returning only |
| 406 | + `overriddenDuration` therefore keeps the historical behavior. |
| 407 | +- Task-concurrent `run()` and `warmup()` use the real clock for their budgets |
| 408 | + and do not inspect `overriddenIterationCost` (neither presence nor value). |
| 409 | + The cost applies per task with `concurrency: 'bench'` and in |
| 410 | + `Task.warmupSync()` regardless of concurrency. |
| 411 | +- Both fields are validated the same way (finite number ≥ 0, `-0` |
| 412 | + included); an invalid value is treated as absent. |
| 413 | +- The cost field must be reported as present by the `in` operator (own or |
| 414 | + inherited). A proxy default for an absent key is not a declared cost. Errors |
| 415 | + while checking or reading this field are treated as an absent cost. |
| 416 | +- The cost does not affect timer-overhead correction or timer diagnostics; |
| 417 | + these operate on samples. `result.totalTime` and `period` also remain |
| 418 | + sample-derived. Returning only the cost leaves samples timer-measured, |
| 419 | + so timer-saturation warnings may still occur. |
| 420 | +- The declared cost is not verified against reality: an iteration whose real |
| 421 | + wall-clock cost is `C` but declared as `O` stretches the run to about |
| 422 | + `time × C / O` when `O < C`, and shortens it when `O > C`, provided |
| 423 | + the time budget dominates the minimum iteration count. |
| 424 | +- **Warning.** Repeated costs of `0` (or `-0`) cannot satisfy a positive |
| 425 | + sequential time budget; tiny positive costs can make it impractical to reach. |
| 426 | + With `time: 0`, the run can finish at the minimum iteration count. The same |
| 427 | + rules apply to warmup. Cancellation from an external timer requires yielding |
| 428 | + to the event loop and cannot interrupt `runSync()`; see |
| 429 | + [Abort During Execution](#abort-during-execution). |
| 430 | + |
361 | 431 | ## Timer Diagnostics |
362 | 432 |
|
363 | 433 | After `bench.run()` (or `runSync()`), each task exposes |
364 | | -`detectedResolution` — the smallest reproducibly observed positive |
365 | | -sample (in ms) among the timer-measured samples, or `undefined` when no |
366 | | -positive timer measurement was seen (e.g. every sample was overridden). |
| 434 | +`detectedResolution`: the smallest positive latency sample occurring at least |
| 435 | +twice, or the smallest positive sample if none repeats. Only timer-measured |
| 436 | +samples after any overhead correction are considered; if none is positive, |
| 437 | +the result is `undefined`. This is a sample-based heuristic, not a guaranteed |
| 438 | +bound on the timer's resolution. |
367 | 439 |
|
368 | 440 | ```ts |
369 | 441 | const task = bench.getTask('foo') |
370 | 442 | console.log(task?.detectedResolution) // e.g. 0.000041 (≈ 41 ns) |
371 | 443 | ``` |
372 | 444 |
|
373 | | -When the timer's resolution dominates a task's measured distribution |
374 | | -(more than half zero samples, fewer than `max(3, min(10, ⌊n / 1000⌋))` |
375 | | -distinct values, or zero MAD with `n > 100`), tinybench dispatches a |
376 | | -`'warning'` event on both the task and the bench, carrying the matching |
| 445 | +With at least 10 such samples, tinybench dispatches a `'warning'` event on |
| 446 | +both the task and the bench when more than half are zero, fewer than |
| 447 | +`max(3, min(10, ⌊n / 1000⌋))` distinct values occur, or MAD is zero with |
| 448 | +`n > 100`. The event carries the matching |
377 | 449 | [`TimerSaturationReason`](https://tinylibs.github.io/tinybench/types/TimerSaturationReason.html): |
378 | 450 |
|
379 | 451 | ```ts |
@@ -467,6 +539,12 @@ await bench.run() |
467 | 539 | // Task will stop after ~1 second instead of running for 10 seconds |
468 | 540 | ``` |
469 | 541 |
|
| 542 | +Timer-triggered cancellation requires the task or a hook to yield to the |
| 543 | +event loop, for example by awaiting I/O. Awaiting an already-resolved promise |
| 544 | +is not sufficient. In `runSync()`, a task or synchronous hook can call |
| 545 | +`controller.abort()` on the associated controller, but an external timer |
| 546 | +cannot interrupt the run. |
| 547 | + |
470 | 548 | ### Abort Events |
471 | 549 |
|
472 | 550 | Both `Bench` and `Task` emit `abort` events when aborted: |
@@ -484,6 +562,9 @@ bench.add( |
484 | 562 | ) |
485 | 563 |
|
486 | 564 | const task = bench.getTask('task') |
| 565 | +if (!task) { |
| 566 | + throw new Error('Task not found') |
| 567 | +} |
487 | 568 |
|
488 | 569 | // Listen for abort events |
489 | 570 | task.addEventListener('abort', () => { |
@@ -498,7 +579,9 @@ controller.abort() |
498 | 579 | await bench.run() |
499 | 580 | ``` |
500 | 581 |
|
501 | | -**Note:** When a task is aborted, `task.result.aborted` will be `true`, and the task will have completed any iterations that were running when the abort signal was received. |
| 582 | +**Note:** An aborted task has `task.result.state` equal to `'aborted'` or |
| 583 | +`'aborted-with-statistics'`. Iterations already in progress may finish before |
| 584 | +the run returns. |
502 | 585 |
|
503 | 586 | ## Prior art |
504 | 587 |
|
|