A benchmarking library that supports high-resolution timers and returns statistically significant results
npx @tessl/cli install tessl/npm-benchmark@2.1.0Benchmark.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.
npm install benchmarkconst Benchmark = require('benchmark');For ES modules:
import Benchmark from 'benchmark';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 });Benchmark.js is built around several key components:
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)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 benchmarksEvent-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;
}// 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);// 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
}