@stdlib/bench-harness
Version:
Benchmark harness.
107 lines (88 loc) • 2.26 kB
JavaScript
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
;
// MODULES //
var isString = require( '@stdlib/assert-is-string' ).isPrimitive;
var copy = require( '@stdlib/utils-copy' );
var Benchmark = require( './../benchmark-class' );
// VARIABLES //
var MIN_TIME = 0.1; // seconds
var ITERATIONS = 10; // 10^1
var MAX_ITERATIONS = 10000000000; // 10^10
// MAIN //
/**
* Determines the number of iterations.
*
* @private
* @param {string} name - benchmark name
* @param {Options} options - benchmark options
* @param {(Function|undefined)} benchmark - function containing benchmark code
* @param {Callback} clbk - callback to invoke after determining number of iterations
* @returns {void}
*/
function iterations( name, options, benchmark, clbk ) {
var opts;
var time;
// Elapsed time (in seconds):
time = 0;
// Create a local copy:
opts = copy( options );
opts.iterations = ITERATIONS;
// Begin running benchmarks:
return next();
/**
* Run a new benchmark.
*
* @private
*/
function next() {
var b = new Benchmark( name, opts, benchmark );
b.on( 'result', onResult );
b.once( 'end', onEnd );
b.run();
}
/**
* Callback invoked upon a `result` event.
*
* @private
* @param {(string|Object)} result - result
*/
function onResult( result ) {
if ( !isString( result ) && result.operator === 'result' ) {
time = result.elapsed;
}
}
/**
* Callback invoked upon an `end` event.
*
* @private
* @returns {void}
*/
function onEnd() {
if (
time < MIN_TIME &&
opts.iterations < MAX_ITERATIONS
) {
opts.iterations *= 10;
return next();
}
clbk( null, opts.iterations );
}
}
// EXPORTS //
module.exports = iterations;