or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

benchmark.mdevents.mdindex.mdsuite.md
tile.json

tessl/npm-benchmark

A benchmarking library that supports high-resolution timers and returns statistically significant results

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/benchmark@2.1.x

To install, run

npx @tessl/cli install tessl/npm-benchmark@2.1.0

index.mddocs/

Benchmark.js

Benchmark.js is a robust JavaScript benchmarking library that supports high-resolution timers and returns statistically significant results. It provides a comprehensive API for measuring and comparing the performance of code snippets with statistical accuracy.

Package Information

  • Package Name: benchmark
  • Package Type: npm
  • Language: JavaScript
  • Installation: npm install benchmark

Core Imports

const Benchmark = require('benchmark');

For ES modules:

import Benchmark from 'benchmark';

Basic Usage

const Benchmark = require('benchmark');

// Single benchmark
const bench = new Benchmark('RegExp#test', function() {
  /o/.test('Hello World!');
});

bench.on('complete', function() {
  console.log(String(this));
}).run();

// Benchmark suite
const suite = new Benchmark.Suite;

suite.add('RegExp#test', function() {
  /o/.test('Hello World!');
})
.add('String#indexOf', function() {
  'Hello World!'.indexOf('o') > -1;
})
.on('cycle', function(event) {
  console.log(String(event.target));
})
.on('complete', function() {
  console.log('Fastest is ' + this.filter('fastest').map('name'));
})
.run({ 'async': true });

Architecture

Benchmark.js is built around several key components:

  • Benchmark Constructor: Core benchmarking functionality for individual tests
  • Suite System: Collection-based benchmark management for comparing multiple tests
  • Event System: Event-driven architecture for monitoring benchmark progress
  • Statistical Analysis: Built-in statistical calculations with confidence intervals
  • High-Resolution Timing: Cross-platform timer support for accurate measurements
  • Deferred Execution: Support for asynchronous benchmarks

Capabilities

Core Benchmarking

Individual benchmark creation and execution with comprehensive timing and statistical analysis.

/**
 * The Benchmark constructor creates a new benchmark instance
 * @param {string} [name] - The name of the benchmark
 * @param {function|string} [fn] - The test function or code string
 * @param {object} [options] - Benchmark options
 */
function Benchmark(name, fn, options);

// Static properties
Benchmark.version; // string: Library version
Benchmark.options; // object: Default benchmark options
Benchmark.platform; // object: Platform information
Benchmark.support; // object: Feature detection
// Properties: browser (boolean), timeout (boolean), decompilation (boolean)

Core Benchmarking

Suite Management

Collection-based benchmark management for organizing and running multiple related benchmarks together.

/**
 * The Suite constructor creates a benchmark suite
 * @param {string} [name] - The name of the suite
 * @param {object} [options] - Suite options
 */
function Benchmark.Suite(name, options);

// Suite methods
suite.add(name, fn, options); // Add benchmark
suite.run(options); // Run all benchmarks
suite.filter(callback); // Filter benchmarks

Suite Management

Event System

Event-driven system for monitoring benchmark and suite execution with detailed progress tracking.

// Event types: 'start', 'cycle', 'complete', 'abort', 'error', 'reset'
benchmark.on(type, listener); // Add event listener
benchmark.emit(type, ...args); // Emit event
suite.on(type, listener); // Suite event listener

// Event object
interface BenchmarkEvent {
  type: string;
  target: Benchmark | Suite;
  timeStamp: number;
}

Event System

Static Utilities

// Utility functions
Benchmark.filter(array, callback); // Filter benchmarks by criteria
Benchmark.invoke(array, methodName, ...args); // Invoke method on all benchmarks
Benchmark.formatNumber(number); // Format number with separators
Benchmark.join(array, separator); // Join benchmark results

// Context creation
Benchmark.runInContext(context); // Create Benchmark in custom context

// Lodash methods (delegated)
Benchmark.each(collection, iterator);
Benchmark.forEach(collection, iterator);
Benchmark.forOwn(object, iterator);
Benchmark.has(object, key);
Benchmark.indexOf(array, value);
Benchmark.map(collection, iterator);
Benchmark.reduce(collection, iterator, accumulator);

Core Types

// Benchmark options
interface BenchmarkOptions {
  async?: boolean;        // Execute asynchronously
  defer?: boolean;        // Use deferred timing
  delay?: number;         // Delay between cycles (seconds)
  id?: string;           // Benchmark identifier
  initCount?: number;    // Initial execution count
  maxTime?: number;      // Maximum execution time (seconds)
  minSamples?: number;   // Minimum sample size
  minTime?: number;      // Minimum execution time (seconds)
  name?: string;         // Benchmark name
  onAbort?: function;    // Abort event handler
  onComplete?: function; // Complete event handler
  onCycle?: function;    // Cycle event handler
  onError?: function;    // Error event handler
  onReset?: function;    // Reset event handler
  onStart?: function;    // Start event handler
  setup?: function|string; // Setup code
  teardown?: function|string; // Teardown code
}

// Statistical results
interface BenchmarkStats {
  deviation: number;     // Standard deviation
  mean: number;         // Sample arithmetic mean
  moe: number;          // Margin of error
  rme: number;          // Relative margin of error (%)
  sample: number[];     // Sample data points
  sem: number;          // Standard error of mean
  variance: number;     // Sample variance
}

// Timing information
interface BenchmarkTimes {
  cycle: number;        // Time for last cycle
  elapsed: number;      // Total elapsed time
  period: number;       // Time per operation
  timeStamp: number;    // Cycle start timestamp
}

// Platform information
interface PlatformInfo {
  description: string;  // User agent string
  layout: string;       // Browser layout engine
  manufacturer: string; // Hardware manufacturer
  name: string;         // Browser/runtime name
  os: string;          // Operating system
  product: string;     // Browser product name
  version: string;     // Version information
}

// Deferred benchmark (for async tests)
interface Deferred {
  benchmark: Benchmark; // The deferred benchmark instance
  cycles: number;       // Number of deferred cycles performed
  elapsed: number;      // Time taken to complete deferred benchmark (seconds)
  timeStamp: number;    // Timestamp when deferred benchmark started (ms)
  resolve(): void;      // Resolve the deferred benchmark
}

// Event object for benchmark events
interface BenchmarkEvent {
  type: string;                    // Event type name
  target: Benchmark | Suite;       // Object that emitted the event
  currentTarget?: Benchmark | Suite; // Current event target
  timeStamp: number;               // Event creation timestamp (ms)
  result?: any;                    // Event result data
  aborted?: boolean;               // Whether event iteration was aborted
  cancelled?: boolean;             // Whether default action was cancelled
}

Environment Support

  • Browsers: Chrome 54+, Firefox 49+, IE 11+, Edge 14+, Safari 9+
  • Node.js: Version 6+
  • Other: PhantomJS 2.1.1+

Dependencies

  • Required: lodash ^4.17.4
  • Optional: platform ^1.3.3 (for enhanced platform detection)
  • Optional: microtime (Node.js - for higher precision timing)