All files / dev runBenchmark.ts

100% Statements 17/17
100% Branches 6/6
100% Functions 4/4
100% Lines 17/17

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43              2x       2x   2x 4x 4x 2x 2x   4x   2x 4x   2x 2x 2x 1x       1x       1x         2x    
import Table from 'cli-table3'
import { formatNumber, Options, Suite } from 'benchmark'
 
export function runBenchmark(
  suites: Record<string, () => any>,
  options?: Options,
) {
  const table = new Table({
    head: ['name', 'ops/sec'],
    colAligns: ['left', 'right'],
  })
  const suite = new Suite()
  let expectFastestName: string | undefined
  for (let name of Object.keys(suites)) {
    const fn = suites[name]
    if (name.endsWith('!fastest')) {
      name = name.replace(/!fastest$/, '')
      expectFastestName = name
    }
    suite.add(name, fn)
  }
  suite.on('cycle', function (event: any) {
    table.push([event.target.name, formatNumber(Math.round(event.target.hz))])
  })
  suite.on('complete', function (this: any) {
    const actualFastestName = this.filter('fastest').map('name')[0]
    if (expectFastestName != null && expectFastestName !== actualFastestName) {
      throw new Error(
        `Expect fastest is ${expectFastestName}, actual fastest is ${actualFastestName}.`,
      )
    }
    console.log(
      table
        .sort(
          (a, b) =>
            (b as any)[1].replace(/,/, '') - (a as any)[1].replace(/,/, ''),
        )
        .toString(),
    )
  })
  suite.run(options)
}