Tinybench

A simple, tiny and lightweight benchmarking library!

README

tinybench


Benchmark your code easily with Tinybench, a simple, tiny and light-weight 7KB (2KB minified and gzipped)
benchmarking library!
You can run your benchmarks in multiple JavaScript runtimes, Tinybench is
completely based on the Web APIs with proper timing using process.hrtime or
performance.now.

- Accurate and precise timing based on the environment
- Event and EventTarget compatible events
- Statistically analyzed values
- Calculated Percentiles
- Fully detailed results
- No dependencies

_In case you need more tiny libraries like tinypool or tinyspy, please consider submitting an RFC_

Installing


  1. ``` sh
  2. $ npm install -D tinybench
  3. ```

Usage


You can start benchmarking by instantiating the Bench class and adding
benchmark tasks to it.

  1. ``` js
  2. import { Bench } from 'tinybench';

  3. const bench = new Bench({ time: 100 });

  4. bench
  5.   .add('switch 1', () => {
  6.     let a = 1;
  7.     let b = 2;
  8.     const c = a;
  9.     a = b;
  10.     b = c;
  11.   })
  12.   .add('switch 2', () => {
  13.     let a = 1;
  14.     let b = 10;
  15.     a = b + a;
  16.     b = a - b;
  17.     a = b - a;
  18.   });

  19. await bench.run();

  20. console.table(bench.tasks.map(({ name, result }) => ({ "Task Name": name, "Average Time (ps)": result?.mean * 1000, "Variance (ps)": result?.variance * 1000 })));

  21. // Output:
  22. // ┌─────────┬────────────┬────────────────────┬────────────────────┐
  23. // │ (index) │ Task Name  │ Average Time (ps)  │   Variance (ps)    │
  24. // ├─────────┼────────────┼────────────────────┼────────────────────┤
  25. // │    0    │ 'switch 1' │ 1.8458325710527104 │ 1.2113875253341617 │
  26. // │    1    │ 'switch 2' │ 1.8746935152109603 │ 1.2254725890767446 │
  27. // └─────────┴────────────┴────────────────────┴────────────────────┘
  28. ```

The add method accepts a task name and a task function, so it can benchmark
it! This method returns a reference to the Bench instance, so it's possible to
use it to create an another task for that instance.

Note that the task name should always be unique in an instance, because Tinybench stores the tasks based
on their names in a Map.

Also note that tinybench does not log any result by default. You can extract the relevant stats
from bench.tasks or any other API after running the benchmark, and process them however you want.

Docs


Bench


The Benchmark instance for keeping track of the benchmark tasks and controlling
them.

Options:

  1. ```ts
  2. export type Options = {
  3.   /**
  4.    * time needed for running a benchmark task (milliseconds) @default 500
  5.    */
  6.   time?: number;

  7.   /**
  8.    * number of times that a task should run if even the time option is finished @default 10
  9.    */
  10.   iterations?: number;

  11.   /**
  12.    * function to get the current timestamp in milliseconds
  13.    */
  14.   now?: () => number;

  15.   /**
  16.    * An AbortSignal for aborting the benchmark
  17.    */
  18.   signal?: AbortSignal;

  19.   /**
  20.    * warmup time (milliseconds) @default 100ms
  21.    */
  22.   warmupTime?: number;

  23.   /**
  24.    * warmup iterations @default 5
  25.    */
  26.   warmupIterations?: number;

  27.   /**
  28.    * setup function to run before each benchmark task (cycle)
  29.    */
  30.   setup?: Hook;

  31.   /**
  32.    * teardown function to run after each benchmark task (cycle)
  33.    */
  34.   teardown?: Hook;
  35. };

  36. export type Hook = (task: Task, mode: "warmup" | "run") => void | Promise<void>;
  37. ```

- async run(): run the added tasks that were registered using the add method
- async warmup(): warm up the benchmark tasks
- reset(): reset each task and remove its result
- add(name: string, fn: Fn): add a benchmark task to the task map
- - `Fn`: `() => any | Promise`
- remove(name: string): remove a benchmark task from the task map
- get results(): (TaskResult | undefined)[]: (getter) tasks results as an array
- get tasks(): Task[]: (getter) tasks as an array
- getTask(name: string): Task | undefined: get a task based on the name

Task


A class that represents each benchmark task in Tinybench. It keeps track of the
results, name, Bench instance, the task function and the number of times the task
function has been executed.

- constructor(bench: Bench, name: string, fn: Fn)
- bench: Bench
- name: string: task name
- fn: Fn: the task function
- runs: number: the number of times the task function has been executed
- result?: TaskResult: the result object
- async run(): run the current task and write the results in Task.result object
- async warmup(): warm up the current task
- `setResult(result: Partial)`: change the result object values
- reset(): reset the task to make the Task.runs a zero-value and remove the Task.result object

TaskResult


the benchmark task result object.

  1. ```ts
  2. export type TaskResult = {

  3.   /*
  4.    * the last error that was thrown while running the task
  5.    */
  6.   error?: unknown;

  7.   /**
  8.    * The amount of time in milliseconds to run the benchmark task (cycle).
  9.    */
  10.   totalTime: number;

  11.   /**
  12.    * the minimum value in the samples
  13.    */
  14.   min: number;
  15.   /**
  16.    * the maximum value in the samples
  17.    */
  18.   max: number;

  19.   /**
  20.    * the number of operations per second
  21.    */
  22.   hz: number;

  23.   /**
  24.    * how long each operation takes (ms)
  25.    */
  26.   period: number;

  27.   /**
  28.    * task samples of each task iteration time (ms)
  29.    */
  30.   samples: number[];

  31.   /**
  32.    * samples mean/average (estimate of the population mean)
  33.    */
  34.   mean: number;

  35.   /**
  36.    * samples variance (estimate of the population variance)
  37.    */
  38.   variance: number;

  39.   /**
  40.    * samples standard deviation (estimate of the population standard deviation)
  41.    */
  42.   sd: number;

  43.   /**
  44.    * standard error of the mean (a.k.a. the standard deviation of the sampling distribution of the sample mean)
  45.    */
  46.   sem: number;

  47.   /**
  48.    * degrees of freedom
  49.    */
  50.   df: number;

  51.   /**
  52.    * critical value of the samples
  53.    */
  54.   critical: number;

  55.   /**
  56.    * margin of error
  57.    */
  58.   moe: number;

  59.   /**
  60.    * relative margin of error
  61.    */
  62.   rme: number;

  63.   /**
  64.    * p75 percentile
  65.    */
  66.   p75: number;

  67.   /**
  68.    * p99 percentile
  69.    */
  70.   p99: number;

  71.   /**
  72.    * p995 percentile
  73.    */
  74.   p995: number;

  75.   /**
  76.    * p999 percentile
  77.    */
  78.   p999: number;
  79. };
  80. ```

Events


Both the Task and Bench objects extend the EventTarget object, so you can attach listeners to different types of events
in each class instance using the universal addEventListener and
removeEventListener.

  1. ```ts
  2. /**
  3. * Bench events
  4. */
  5. export type BenchEvents =
  6.   | "abort" // when a signal aborts
  7.   | "complete" // when running a benchmark finishes
  8.   | "error" // when the benchmark task throws
  9.   | "reset" // when the reset function gets called
  10.   | "start" // when running the benchmarks gets started
  11.   | "warmup" // when the benchmarks start getting warmed up (before start)
  12.   | "cycle" // when running each benchmark task gets done (cycle)
  13.   | "add" // when a Task gets added to the Bench
  14.   | "remove"; // when a Task gets removed of the Bench

  15. /**
  16. * task events
  17. */
  18. export type TaskEvents =
  19.   | "abort"
  20.   | "complete"
  21.   | "error"
  22.   | "reset"
  23.   | "start"
  24.   | "warmup"
  25.   | "cycle";
  26. ```

For instance:

  1. ``` js
  2. // runs on each benchmark task's cycle
  3. bench.addEventListener("cycle", (e) => {
  4.   const task = e.task!;
  5. });

  6. // runs only on this benchmark task's cycle
  7. task.addEventListener("cycle", (e) => {
  8.   const task = e.task!;
  9. });
  10. ```

BenchEvent


  1. ```ts
  2. export type BenchEvent = Event & {
  3.   task: Task | null;
  4. };
  5. ```

Prior art



Authors


------------------------------------------------------------------------------------------------------------------------------------------------

Credits


-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

Contributing


Feel free to create issues/discussions and then PRs for the project!