"Fossies" - the Fresh Open Source Software Archive  

Source code changes of the file "vendor/benchmark.js/benchmark.js" between
lodash-3.0.0.tar.gz and lodash-4.0.0.tar.gz

About: lodash is a modern JavaScript utility library delivering modularity, performance, & extras.

benchmark.js  (lodash-3.0.0):benchmark.js  (lodash-4.0.0)
/*! /*!
* Benchmark.js v2.0.0-pre <http://benchmarkjs.com/> * Benchmark.js v2.0.0-pre <http://benchmarkjs.com/>
* Copyright 2010-2015 Mathias Bynens <http://mths.be/> * Copyright 2010-2015 Mathias Bynens <http://mths.be/>
* Based on JSLitmus.js, copyright Robert Kieffer <http://broofa.com/> * Based on JSLitmus.js, copyright Robert Kieffer <http://broofa.com/>
* Modified by John-David Dalton <http://allyoucanleet.com/> * Modified by John-David Dalton <http://allyoucanleet.com/>
* Available under MIT license <http://mths.be/mit> * Available under MIT license <http://mths.be/mit>
*/ */
;(function() { ;(function() {
'use strict'; 'use strict';
/** Used as a safe reference for `undefined` in pre ES5 environments */ /** Used as a safe reference for `undefined` in pre ES5 environments. */
var undefined; var undefined;
/** Used to determine if values are of the language type Object */ /** Used to determine if values are of the language type Object. */
var objectTypes = { var objectTypes = {
'function': true, 'function': true,
'object': true 'object': true
}; };
/** Used as a reference to the global object */ /** Used as a reference to the global object. */
var root = (objectTypes[typeof window] && window) || this; var root = (objectTypes[typeof window] && window) || this;
/** Detect free variable `define` */ /** Detect free variable `define`. */
var freeDefine = typeof define == 'function' && typeof define.amd == 'object' && define.amd && define; var freeDefine = typeof define == 'function' && typeof define.amd == 'object' && define.amd && define;
/** Detect free variable `exports` */ /** Detect free variable `exports`. */
var freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports; var freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports;
/** Detect free variable `module` */ /** Detect free variable `module`. */
var freeModule = objectTypes[typeof module] && module && !module.nodeType && m odule; var freeModule = objectTypes[typeof module] && module && !module.nodeType && m odule;
/** Detect free variable `global` from Node.js or Browserified code and use it as `root` */ /** Detect free variable `global` from Node.js or Browserified code and use it as `root`. */
var freeGlobal = freeExports && freeModule && typeof global == 'object' && glo bal; var freeGlobal = freeExports && freeModule && typeof global == 'object' && glo bal;
if (freeGlobal && (freeGlobal.global === freeGlobal || freeGlobal.window === f reeGlobal || freeGlobal.self === freeGlobal)) { if (freeGlobal && (freeGlobal.global === freeGlobal || freeGlobal.window === f reeGlobal || freeGlobal.self === freeGlobal)) {
root = freeGlobal; root = freeGlobal;
} }
/** Detect free variable `require` */ /** Detect free variable `require`. */
var freeRequire = typeof require == 'function' && require; var freeRequire = typeof require == 'function' && require;
/** Used to assign each benchmark an incrimented id */ /** Used to assign each benchmark an incremented id. */
var counter = 0; var counter = 0;
/** Detect the popular CommonJS extension `module.exports` */ /** Detect the popular CommonJS extension `module.exports`. */
var moduleExports = freeModule && freeModule.exports === freeExports && freeEx ports; var moduleExports = freeModule && freeModule.exports === freeExports && freeEx ports;
/** Used to detect primitive types */ /** Used to detect primitive types. */
var rePrimitive = /^(?:boolean|number|string|undefined)$/; var rePrimitive = /^(?:boolean|number|string|undefined)$/;
/** Used to make every compiled test unique */ /** Used to make every compiled test unique. */
var uidCounter = 0; var uidCounter = 0;
/** Used to assign default `context` object properties */ /** Used to assign default `context` object properties. */
var contextProps = [ var contextProps = [
'Array', 'Date', 'Function', 'Math', 'Object', 'RegExp', 'String', '_', 'Array', 'Date', 'Function', 'Math', 'Object', 'RegExp', 'String', '_',
'clearTimeout', 'chrome', 'chromium', 'document', 'java', 'navigator', 'clearTimeout', 'chrome', 'chromium', 'document', 'navigator', 'phantom',
'phantom', 'platform', 'process', 'runtime', 'setTimeout' 'platform', 'process', 'runtime', 'setTimeout'
]; ];
/** Used to avoid hz of Infinity */ /** Used to avoid hz of Infinity. */
var divisors = { var divisors = {
'1': 4096, '1': 4096,
'2': 512, '2': 512,
'3': 64, '3': 64,
'4': 8, '4': 8,
'5': 0 '5': 0
}; };
/** /**
* T-Distribution two-tailed critical values for 95% confidence * T-Distribution two-tailed critical values for 95% confidence.
* http://www.itl.nist.gov/div898/handbook/eda/section3/eda3672.htm * For more info see http://www.itl.nist.gov/div898/handbook/eda/section3/eda3
672.htm.
*/ */
var tTable = { var tTable = {
'1': 12.706, '2': 4.303, '3': 3.182, '4': 2.776, '5': 2.571, '6': 2.44 7, '1': 12.706, '2': 4.303, '3': 3.182, '4': 2.776, '5': 2.571, '6': 2.44 7,
'7': 2.365, '8': 2.306, '9': 2.262, '10': 2.228, '11': 2.201, '12': 2.17 9, '7': 2.365, '8': 2.306, '9': 2.262, '10': 2.228, '11': 2.201, '12': 2.17 9,
'13': 2.16, '14': 2.145, '15': 2.131, '16': 2.12, '17': 2.11, '18': 2.10 1, '13': 2.16, '14': 2.145, '15': 2.131, '16': 2.12, '17': 2.11, '18': 2.10 1,
'19': 2.093, '20': 2.086, '21': 2.08, '22': 2.074, '23': 2.069, '24': 2.06 4, '19': 2.093, '20': 2.086, '21': 2.08, '22': 2.074, '23': 2.069, '24': 2.06 4,
'25': 2.06, '26': 2.056, '27': 2.052, '28': 2.048, '29': 2.045, '30': 2.04 2, '25': 2.06, '26': 2.056, '27': 2.052, '28': 2.048, '29': 2.045, '30': 2.04 2,
'infinity': 1.96 'infinity': 1.96
}; };
/** /**
* Critical Mann-Whitney U-values for 95% confidence * Critical Mann-Whitney U-values for 95% confidence.
* http://www.saburchill.com/IBbiology/stats/003.html * For more info see http://www.saburchill.com/IBbiology/stats/003.html.
*/ */
var uTable = { var uTable = {
'5': [0, 1, 2], '5': [0, 1, 2],
'6': [1, 2, 3, 5], '6': [1, 2, 3, 5],
'7': [1, 3, 5, 6, 8], '7': [1, 3, 5, 6, 8],
'8': [2, 4, 6, 8, 10, 13], '8': [2, 4, 6, 8, 10, 13],
'9': [2, 4, 7, 10, 12, 15, 17], '9': [2, 4, 7, 10, 12, 15, 17],
'10': [3, 5, 8, 11, 14, 17, 20, 23], '10': [3, 5, 8, 11, 14, 17, 20, 23],
'11': [3, 6, 9, 13, 16, 19, 23, 26, 30], '11': [3, 6, 9, 13, 16, 19, 23, 26, 30],
'12': [4, 7, 11, 14, 18, 22, 26, 29, 33, 37], '12': [4, 7, 11, 14, 18, 22, 26, 29, 33, 37],
skipping to change at line 126 skipping to change at line 126
/** /**
* Create a new `Benchmark` function using the given `context` object. * Create a new `Benchmark` function using the given `context` object.
* *
* @static * @static
* @memberOf Benchmark * @memberOf Benchmark
* @param {Object} [context=root] The context object. * @param {Object} [context=root] The context object.
* @returns {Function} Returns a new `Benchmark` function. * @returns {Function} Returns a new `Benchmark` function.
*/ */
function runInContext(context) { function runInContext(context) {
// exit early if unable to acquire lodash // Exit early if unable to acquire lodash.
var _ = context && context._ || req('lodash') || root._; var _ = context && context._ || req('lodash-compat') || req('lodash') || roo
t._;
if (!_) { if (!_) {
Benchmark.runInContext = runInContext; Benchmark.runInContext = runInContext;
return Benchmark; return Benchmark;
} }
// Avoid issues with some ES3 environments that attempt to use values, named // Avoid issues with some ES3 environments that attempt to use values, named
// after built-in constructors like `Object`, for the creation of literals. // after built-in constructors like `Object`, for the creation of literals.
// ES5 clears this up by stating that literals must use built-in constructor s. // ES5 clears this up by stating that literals must use built-in constructor s.
// See http://es5.github.io/#x11.1.5. // See http://es5.github.io/#x11.1.5.
context = context ? _.defaults(root.Object(), context, _.pick(root, contextP rops)) : root; context = context ? _.defaults(root.Object(), context, _.pick(root, contextP rops)) : root;
/** Native constructor references */ /** Native constructor references. */
var Array = context.Array, var Array = context.Array,
Date = context.Date, Date = context.Date,
Function = context.Function, Function = context.Function,
Math = context.Math, Math = context.Math,
Object = context.Object, Object = context.Object,
RegExp = context.RegExp, RegExp = context.RegExp,
String = context.String; String = context.String;
/** Used for `Array` and `Object` method references */ /** Used for `Array` and `Object` method references. */
var arrayRef = [], var arrayRef = [],
objectProto = Object.prototype; objectProto = Object.prototype;
/** Native method shortcuts */ /** Native method shortcuts. */
var abs = Math.abs, var abs = Math.abs,
clearTimeout = context.clearTimeout, clearTimeout = context.clearTimeout,
floor = Math.floor, floor = Math.floor,
log = Math.log, log = Math.log,
max = Math.max, max = Math.max,
min = Math.min, min = Math.min,
pow = Math.pow, pow = Math.pow,
push = arrayRef.push, push = arrayRef.push,
setTimeout = context.setTimeout, setTimeout = context.setTimeout,
shift = arrayRef.shift, shift = arrayRef.shift,
slice = arrayRef.slice, slice = arrayRef.slice,
sqrt = Math.sqrt, sqrt = Math.sqrt,
toString = objectProto.toString, toString = objectProto.toString,
unshift = arrayRef.unshift; unshift = arrayRef.unshift;
/** Detect DOM document object */ /** Detect DOM document object. */
var doc = isHostType(context, 'document') && context.document; var doc = isHostType(context, 'document') && context.document;
/** Used to access Wade Simmons' Node.js `microtime` module */ /** Used to access Wade Simmons' Node.js `microtime` module. */
var microtimeObject = req('microtime'); var microtimeObject = req('microtime');
/** Used to access Node.js's high resolution timer */ /** Used to access Node.js's high resolution timer. */
var processObject = isHostType(context, 'process') && context.process; var processObject = isHostType(context, 'process') && context.process;
/** Used to prevent a `removeChild` memory leak in IE < 9 */ /** Used to prevent a `removeChild` memory leak in IE < 9. */
var trash = doc && doc.createElement('div'); var trash = doc && doc.createElement('div');
/** Used to integrity check compiled tests */ /** Used to integrity check compiled tests. */
var uid = 'uid' + _.now(); var uid = 'uid' + _.now();
/** Used to avoid infinite recursion when methods call each other */ /** Used to avoid infinite recursion when methods call each other. */
var calledBy = {}; var calledBy = {};
/** /**
* An object used to flag environments/features. * An object used to flag environments/features.
* *
* @static * @static
* @memberOf Benchmark * @memberOf Benchmark
* @type Object * @type Object
*/ */
var support = {}; var support = {};
skipping to change at line 205 skipping to change at line 205
/** /**
* Detect if running in a browser environment. * Detect if running in a browser environment.
* *
* @memberOf Benchmark.support * @memberOf Benchmark.support
* @type boolean * @type boolean
*/ */
support.browser = doc && isHostType(context, 'navigator') && !isHostType(c ontext, 'phantom'); support.browser = doc && isHostType(context, 'navigator') && !isHostType(c ontext, 'phantom');
/** /**
* Detect if Java is enabled/exposed.
*
* @memberOf Benchmark.support
* @type boolean
*/
support.java = isClassOf(context.java, 'JavaPackage');
/**
* Detect if the Timers API exists. * Detect if the Timers API exists.
* *
* @memberOf Benchmark.support * @memberOf Benchmark.support
* @type boolean * @type boolean
*/ */
support.timeout = isHostType(context, 'setTimeout') && isHostType(context, 'clearTimeout'); support.timeout = isHostType(context, 'setTimeout') && isHostType(context, 'clearTimeout');
/** /**
* Detect if `Array#unshift` returns the new length of the array (all but
IE < 8).
*
* @memberOf Benchmark.support
* @type boolean
*/
support.unshiftResult = !![].unshift(1);
/**
* Detect if function decompilation is support. * Detect if function decompilation is support.
* *
* @name decompilation * @name decompilation
* @memberOf Benchmark.support * @memberOf Benchmark.support
* @type boolean * @type boolean
*/ */
try { try {
// Safari 2.x removes commas in object literals // Safari 2.x removes commas in object literals from `Function#toString`
// from `Function#toString` results results.
// http://webk.it/11609 // See http://webk.it/11609 for more details.
// Firefox 3.6 and Opera 9.25 strip grouping // Firefox 3.6 and Opera 9.25 strip grouping parentheses from `Function#
// parentheses from `Function#toString` results toString` results.
// http://bugzil.la/559438 // See http://bugzil.la/559438 for more details.
support.decompilation = Function( support.decompilation = Function(
('return (' + (function(x) { return { 'x': '' + (1 + x) + '', 'y': 0 } ; }) + ')') ('return (' + (function(x) { return { 'x': '' + (1 + x) + '', 'y': 0 } ; }) + ')')
// avoid issues with code added by Istanbul // Avoid issues with code added by Istanbul.
.replace(/__cov__[^;]+;/g, '') .replace(/__cov__[^;]+;/g, '')
)()(0).x === '1'; )()(0).x === '1';
} catch(e) { } catch(e) {
support.decompilation = false; support.decompilation = false;
} }
}()); }());
/** /**
* Timer object used by `clock()` and `Deferred#resolve`. * Timer object used by `clock()` and `Deferred#resolve`.
* *
skipping to change at line 276 skipping to change at line 258
*/ */
'ns': Date, 'ns': Date,
/** /**
* Starts the deferred timer. * Starts the deferred timer.
* *
* @private * @private
* @memberOf timer * @memberOf timer
* @param {Object} deferred The deferred instance. * @param {Object} deferred The deferred instance.
*/ */
'start': null, // lazy defined in `clock()` 'start': null, // Lazy defined in `clock()`.
/** /**
* Stops the deferred timer. * Stops the deferred timer.
* *
* @private * @private
* @memberOf timer * @memberOf timer
* @param {Object} deferred The deferred instance. * @param {Object} deferred The deferred instance.
*/ */
'stop': null // lazy defined in `clock()` 'stop': null // Lazy defined in `clock()`.
}; };
/*------------------------------------------------------------------------*/ /*------------------------------------------------------------------------*/
/** /**
* The Benchmark constructor. * The Benchmark constructor.
* *
* Note: The Benchmark constructor exposes a handful of lodash methods to * Note: The Benchmark constructor exposes a handful of lodash methods to
* make working with arrays, collections, and objects easier. The lodash * make working with arrays, collections, and objects easier. The lodash
* methods are: * methods are:
skipping to change at line 375 skipping to change at line 357
* }); * });
* *
* // a test's `this` binding is set to the benchmark instance * // a test's `this` binding is set to the benchmark instance
* var bench = new Benchmark('foo', function() { * var bench = new Benchmark('foo', function() {
* 'My name is '.concat(this.name); // "My name is foo" * 'My name is '.concat(this.name); // "My name is foo"
* }); * });
*/ */
function Benchmark(name, fn, options) { function Benchmark(name, fn, options) {
var bench = this; var bench = this;
// allow instance creation without the `new` operator // Allow instance creation without the `new` operator.
if (bench == null || bench.constructor != Benchmark) { if (bench == null || bench.constructor != Benchmark) {
return new Benchmark(name, fn, options); return new Benchmark(name, fn, options);
} }
// juggle arguments // Juggle arguments.
if (_.isPlainObject(name)) { if (_.isPlainObject(name)) {
// 1 argument (options) // 1 argument (options).
options = name; options = name;
} }
else if (_.isFunction(name)) { else if (_.isFunction(name)) {
// 2 arguments (fn, options) // 2 arguments (fn, options).
options = fn; options = fn;
fn = name; fn = name;
} }
else if (_.isPlainObject(fn)) { else if (_.isPlainObject(fn)) {
// 2 arguments (name, options) // 2 arguments (name, options).
options = fn; options = fn;
fn = null; fn = null;
bench.name = name; bench.name = name;
} }
else { else {
// 3 arguments (name, fn [, options]) // 3 arguments (name, fn [, options]).
bench.name = name; bench.name = name;
} }
setOptions(bench, options); setOptions(bench, options);
bench.id || (bench.id = ++counter); bench.id || (bench.id = ++counter);
bench.fn == null && (bench.fn = fn); bench.fn == null && (bench.fn = fn);
bench.stats = cloneDeep(bench.stats); bench.stats = cloneDeep(bench.stats);
bench.times = cloneDeep(bench.times); bench.times = cloneDeep(bench.times);
} }
skipping to change at line 487 skipping to change at line 469
* // called when reset * // called when reset
* 'onReset': onReset, * 'onReset': onReset,
* *
* // called when the suite completes running * // called when the suite completes running
* 'onComplete': onComplete * 'onComplete': onComplete
* }); * });
*/ */
function Suite(name, options) { function Suite(name, options) {
var suite = this; var suite = this;
// allow instance creation without the `new` operator // Allow instance creation without the `new` operator.
if (suite == null || suite.constructor != Suite) { if (suite == null || suite.constructor != Suite) {
return new Suite(name, options); return new Suite(name, options);
} }
// juggle arguments // Juggle arguments.
if (_.isPlainObject(name)) { if (_.isPlainObject(name)) {
// 1 argument (options) // 1 argument (options).
options = name; options = name;
} else { } else {
// 2 arguments (name [, options]) // 2 arguments (name [, options]).
suite.name = name; suite.name = name;
} }
setOptions(suite, options); setOptions(suite, options);
} }
/*------------------------------------------------------------------------*/ /*------------------------------------------------------------------------*/
/** /**
* A deep clone utility. * A specialized version of `_.cloneDeep` which only clones arrays and plain
* objects assigning all other values by reference.
* *
* @private * @private
* @param {*} value The value to clone. * @param {*} value The value to clone.
* @returns {*} The cloned value. * @returns {*} The cloned value.
*/ */
var cloneDeep = _.partial(_.cloneDeep, _, function(value) { var cloneDeep = _.partial(_.cloneDeepWith || _.cloneDeep, _, function(value)
// only clone primitives, arrays, and plain objects {
// Only clone primitives, arrays, and plain objects.
return (_.isObject(value) && !_.isArray(value) && !_.isPlainObject(value)) return (_.isObject(value) && !_.isArray(value) && !_.isPlainObject(value))
? value ? value
: undefined; : undefined;
}); });
/** /**
* Creates a function from the given arguments string and body. * Creates a function from the given arguments string and body.
* *
* @private * @private
* @param {string} args The comma separated function arguments. * @param {string} args The comma separated function arguments.
* @param {string} body The function body. * @param {string} body The function body.
* @returns {Function} The new function. * @returns {Function} The new function.
*/ */
function createFunction() { function createFunction() {
// lazy define // Lazy define.
createFunction = function(args, body) { createFunction = function(args, body) {
var result, var result,
anchor = freeDefine ? freeDefine.amd : Benchmark, anchor = freeDefine ? freeDefine.amd : Benchmark,
prop = uid + 'createFunction'; prop = uid + 'createFunction';
runScript((freeDefine ? 'define.amd.' : 'Benchmark.') + prop + '=functio n(' + args + '){' + body + '}'); runScript((freeDefine ? 'define.amd.' : 'Benchmark.') + prop + '=functio n(' + args + '){' + body + '}');
result = anchor[prop]; result = anchor[prop];
delete anchor[prop]; delete anchor[prop];
return result; return result;
}; };
// fix JaegerMonkey bug // Fix JaegerMonkey bug.
// http://bugzil.la/639720 // For more information see http://bugzil.la/639720.
createFunction = support.browser && (createFunction('', 'return"' + uid + '"') || _.noop)() == uid ? createFunction : Function; createFunction = support.browser && (createFunction('', 'return"' + uid + '"') || _.noop)() == uid ? createFunction : Function;
return createFunction.apply(null, arguments); return createFunction.apply(null, arguments);
} }
/** /**
* Delay the execution of a function based on the benchmark's `delay` proper ty. * Delay the execution of a function based on the benchmark's `delay` proper ty.
* *
* @private * @private
* @param {Object} bench The benchmark instance. * @param {Object} bench The benchmark instance.
* @param {Object} fn The function to execute. * @param {Object} fn The function to execute.
skipping to change at line 603 skipping to change at line 586
* *
* @private * @private
* @param {Function} fn The function. * @param {Function} fn The function.
* @returns {string} The function's source code. * @returns {string} The function's source code.
*/ */
function getSource(fn) { function getSource(fn) {
var result = ''; var result = '';
if (isStringable(fn)) { if (isStringable(fn)) {
result = String(fn); result = String(fn);
} else if (support.decompilation) { } else if (support.decompilation) {
// escape the `{` for Firefox 1 // Escape the `{` for Firefox 1.
result = _.result(/^[^{]+\{([\s\S]*)\}\s*$/.exec(fn), 1); result = _.result(/^[^{]+\{([\s\S]*)\}\s*$/.exec(fn), 1);
} }
// trim string // Trim string.
result = (result || '').replace(/^\s+|\s+$/g, ''); result = (result || '').replace(/^\s+|\s+$/g, '');
// detect strings containing only the "use strict" directive // Detect strings containing only the "use strict" directive.
return /^(?:\/\*+[\w\W]*?\*\/|\/\/.*?[\n\r\u2028\u2029]|\s)*(["'])use stri ct\1;?$/.test(result) return /^(?:\/\*+[\w\W]*?\*\/|\/\/.*?[\n\r\u2028\u2029]|\s)*(["'])use stri ct\1;?$/.test(result)
? '' ? ''
: result; : result;
} }
/** /**
* Checks if an object is of the specified class. * Checks if an object is of the specified class.
* *
* @private * @private
* @param {*} value The value to check. * @param {*} value The value to check.
skipping to change at line 657 skipping to change at line 640
* *
* @private * @private
* @param {*} value The value to check. * @param {*} value The value to check.
* @returns {boolean} Returns `true` if the value can be coerced, else `fals e`. * @returns {boolean} Returns `true` if the value can be coerced, else `fals e`.
*/ */
function isStringable(value) { function isStringable(value) {
return _.isString(value) || (_.has(value, 'toString') && _.isFunction(valu e.toString)); return _.isString(value) || (_.has(value, 'toString') && _.isFunction(valu e.toString));
} }
/** /**
* A wrapper around `require()` to suppress `module missing` errors. * A wrapper around `require` to suppress `module missing` errors.
* *
* @private * @private
* @param {string} id The module id. * @param {string} id The module id.
* @returns {*} The exported module or `null`. * @returns {*} The exported module or `null`.
*/ */
function req(id) { function req(id) {
try { try {
var result = freeExports && freeRequire(id); var result = freeExports && freeRequire(id);
} catch(e) {} } catch(e) {}
return result || null; return result || null;
skipping to change at line 688 skipping to change at line 671
script = doc.createElement('script'), script = doc.createElement('script'),
sibling = doc.getElementsByTagName('script')[0], sibling = doc.getElementsByTagName('script')[0],
parent = sibling.parentNode, parent = sibling.parentNode,
prop = uid + 'runScript', prop = uid + 'runScript',
prefix = '(' + (freeDefine ? 'define.amd.' : 'Benchmark.') + prop + '| |function(){})();'; prefix = '(' + (freeDefine ? 'define.amd.' : 'Benchmark.') + prop + '| |function(){})();';
// Firefox 2.0.0.2 cannot use script injection as intended because it exec utes // Firefox 2.0.0.2 cannot use script injection as intended because it exec utes
// asynchronously, but that's OK because script injection is only used to avoid // asynchronously, but that's OK because script injection is only used to avoid
// the previously commented JaegerMonkey bug. // the previously commented JaegerMonkey bug.
try { try {
// remove the inserted script *before* running the code to avoid differe nces // Remove the inserted script *before* running the code to avoid differe nces
// in the expected script element count/order of the document. // in the expected script element count/order of the document.
script.appendChild(doc.createTextNode(prefix + code)); script.appendChild(doc.createTextNode(prefix + code));
anchor[prop] = function() { destroyElement(script); }; anchor[prop] = function() { destroyElement(script); };
} catch(e) { } catch(e) {
parent = parent.cloneNode(false); parent = parent.cloneNode(false);
sibling = null; sibling = null;
script.text = code; script.text = code;
} }
parent.insertBefore(script, sibling); parent.insertBefore(script, sibling);
delete anchor[prop]; delete anchor[prop];
skipping to change at line 713 skipping to change at line 696
* *
* @private * @private
* @param {Object} object The benchmark or suite instance. * @param {Object} object The benchmark or suite instance.
* @param {Object} [options={}] Options object. * @param {Object} [options={}] Options object.
*/ */
function setOptions(object, options) { function setOptions(object, options) {
options = object.options = _.assign({}, cloneDeep(object.constructor.optio ns), cloneDeep(options)); options = object.options = _.assign({}, cloneDeep(object.constructor.optio ns), cloneDeep(options));
_.forOwn(options, function(value, key) { _.forOwn(options, function(value, key) {
if (value != null) { if (value != null) {
// add event listeners // Add event listeners.
if (/^on[A-Z]/.test(key)) { if (/^on[A-Z]/.test(key)) {
_.each(key.split(' '), function(key) { _.each(key.split(' '), function(key) {
object.on(key.slice(2).toLowerCase(), value); object.on(key.slice(2).toLowerCase(), value);
}); });
} else if (!_.has(object, key)) { } else if (!_.has(object, key)) {
object[key] = cloneDeep(value); object[key] = cloneDeep(value);
} }
} }
}); });
} }
skipping to change at line 738 skipping to change at line 721
* Handles cycling/completing the deferred benchmark. * Handles cycling/completing the deferred benchmark.
* *
* @memberOf Benchmark.Deferred * @memberOf Benchmark.Deferred
*/ */
function resolve() { function resolve() {
var deferred = this, var deferred = this,
clone = deferred.benchmark, clone = deferred.benchmark,
bench = clone._original; bench = clone._original;
if (bench.aborted) { if (bench.aborted) {
// cycle() -> clone cycle/complete event -> compute()'s invoked bench.ru n() cycle/complete // cycle() -> clone cycle/complete event -> compute()'s invoked bench.ru n() cycle/complete.
deferred.teardown(); deferred.teardown();
clone.running = false; clone.running = false;
cycle(deferred); cycle(deferred);
} }
else if (++deferred.cycles < clone.count) { else if (++deferred.cycles < clone.count) {
clone.compiled.call(deferred, context, timer); clone.compiled.call(deferred, context, timer);
} }
else { else {
timer.stop(deferred); timer.stop(deferred);
deferred.teardown(); deferred.teardown();
skipping to change at line 762 skipping to change at line 745
/*------------------------------------------------------------------------*/ /*------------------------------------------------------------------------*/
/** /**
* A generic `Array#filter` like method. * A generic `Array#filter` like method.
* *
* @static * @static
* @memberOf Benchmark * @memberOf Benchmark
* @param {Array} array The array to iterate over. * @param {Array} array The array to iterate over.
* @param {Function|string} callback The function/alias called per iteration . * @param {Function|string} callback The function/alias called per iteration .
* @param {*} thisArg The `this` binding for the callback.
* @returns {Array} A new array of values that passed callback filter. * @returns {Array} A new array of values that passed callback filter.
* @example * @example
* *
* // get odd numbers * // get odd numbers
* Benchmark.filter([1, 2, 3, 4, 5], function(n) { * Benchmark.filter([1, 2, 3, 4, 5], function(n) {
* return n % 2; * return n % 2;
* }); // -> [1, 3, 5]; * }); // -> [1, 3, 5];
* *
* // get fastest benchmarks * // get fastest benchmarks
* Benchmark.filter(benches, 'fastest'); * Benchmark.filter(benches, 'fastest');
* *
* // get slowest benchmarks * // get slowest benchmarks
* Benchmark.filter(benches, 'slowest'); * Benchmark.filter(benches, 'slowest');
* *
* // get benchmarks that completed without erroring * // get benchmarks that completed without erroring
* Benchmark.filter(benches, 'successful'); * Benchmark.filter(benches, 'successful');
*/ */
function filter(array, callback, thisArg) { function filter(array, callback) {
if (callback === 'successful') { if (callback === 'successful') {
// callback to exclude those that are errored, unrun, or have hz of Infi nity // Callback to exclude those that are errored, unrun, or have hz of Infi nity.
callback = function(bench) { callback = function(bench) {
return bench.cycles && _.isFinite(bench.hz); return bench.cycles && _.isFinite(bench.hz);
}; };
} }
else if (callback === 'fastest' || callback === 'slowest') { else if (callback === 'fastest' || callback === 'slowest') {
// get successful, sort by period + margin of error, and filter fastest/ slowest // Get successful, sort by period + margin of error, and filter fastest/ slowest.
var result = filter(array, 'successful').sort(function(a, b) { var result = filter(array, 'successful').sort(function(a, b) {
a = a.stats; b = b.stats; a = a.stats; b = b.stats;
return (a.mean + a.moe > b.mean + b.moe ? 1 : -1) * (callback === 'fas test' ? 1 : -1); return (a.mean + a.moe > b.mean + b.moe ? 1 : -1) * (callback === 'fas test' ? 1 : -1);
}); });
return _.filter(result, function(bench) { return _.filter(result, function(bench) {
return result[0].compare(bench) == 0; return result[0].compare(bench) == 0;
}); });
} }
return _.filter(array, callback, thisArg); return _.filter(array, callback);
} }
/** /**
* Converts a number to a more readable comma-separated string representatio n. * Converts a number to a more readable comma-separated string representatio n.
* *
* @static * @static
* @memberOf Benchmark * @memberOf Benchmark
* @param {number} number The number to convert. * @param {number} number The number to convert.
* @returns {string} The more readable string representation. * @returns {string} The more readable string representation.
*/ */
skipping to change at line 871 skipping to change at line 853
result = _.toArray(benches); result = _.toArray(benches);
/** /**
* Invokes the method of the current object and if synchronous, fetches th e next. * Invokes the method of the current object and if synchronous, fetches th e next.
*/ */
function execute() { function execute() {
var listeners, var listeners,
async = isAsync(bench); async = isAsync(bench);
if (async) { if (async) {
// use `getNext` as the first listener // Use `getNext` as the first listener.
bench.on('complete', getNext); bench.on('complete', getNext);
listeners = bench.events.complete; listeners = bench.events.complete;
listeners.splice(0, 0, listeners.pop()); listeners.splice(0, 0, listeners.pop());
} }
// execute method // Execute method.
result[index] = _.isFunction(bench && bench[name]) ? bench[name].apply(b ench, args) : undefined; result[index] = _.isFunction(bench && bench[name]) ? bench[name].apply(b ench, args) : undefined;
// if synchronous return `true` until finished // If synchronous return `true` until finished.
return !async && getNext(); return !async && getNext();
} }
/** /**
* Fetches the next bench or executes `onComplete` callback. * Fetches the next bench or executes `onComplete` callback.
*/ */
function getNext(event) { function getNext(event) {
var cycleEvent, var cycleEvent,
last = bench, last = bench,
async = isAsync(last); async = isAsync(last);
if (async) { if (async) {
last.off('complete', getNext); last.off('complete', getNext);
last.emit('complete'); last.emit('complete');
} }
// emit "cycle" event // Emit "cycle" event.
eventProps.type = 'cycle'; eventProps.type = 'cycle';
eventProps.target = last; eventProps.target = last;
cycleEvent = Event(eventProps); cycleEvent = Event(eventProps);
options.onCycle.call(benches, cycleEvent); options.onCycle.call(benches, cycleEvent);
// choose next benchmark if not exiting early // Choose next benchmark if not exiting early.
if (!cycleEvent.aborted && raiseIndex() !== false) { if (!cycleEvent.aborted && raiseIndex() !== false) {
bench = queued ? benches[0] : result[index]; bench = queued ? benches[0] : result[index];
if (isAsync(bench)) { if (isAsync(bench)) {
delay(bench, execute); delay(bench, execute);
} }
else if (async) { else if (async) {
// resume execution if previously asynchronous but now synchronous // Resume execution if previously asynchronous but now synchronous.
while (execute()) {} while (execute()) {}
} }
else { else {
// continue synchronous execution // Continue synchronous execution.
return true; return true;
} }
} else { } else {
// emit "complete" event // Emit "complete" event.
eventProps.type = 'complete'; eventProps.type = 'complete';
options.onComplete.call(benches, Event(eventProps)); options.onComplete.call(benches, Event(eventProps));
} }
// When used as a listener `event.aborted = true` will cancel the rest o f // When used as a listener `event.aborted = true` will cancel the rest o f
// the "complete" listeners because they were already called above and w hen // the "complete" listeners because they were already called above and w hen
// used as part of `getNext` the `return false` will exit the execution while-loop. // used as part of `getNext` the `return false` will exit the execution while-loop.
if (event) { if (event) {
event.aborted = true; event.aborted = true;
} else { } else {
return false; return false;
} }
} }
/** /**
* Checks if invoking `Benchmark#run` with asynchronous cycles. * Checks if invoking `Benchmark#run` with asynchronous cycles.
*/ */
function isAsync(object) { function isAsync(object) {
// avoid using `instanceof` here because of IE memory leak issues with h ost objects // Avoid using `instanceof` here because of IE memory leak issues with h ost objects.
var async = args[0] && args[0].async; var async = args[0] && args[0].async;
return Object(object).constructor == Benchmark && name == 'run' && return Object(object).constructor == Benchmark && name == 'run' &&
((async == null ? object.options.async : async) && support.timeout || object.defer); ((async == null ? object.options.async : async) && support.timeout || object.defer);
} }
/** /**
* Raises `index` to the next defined index or returns `false`. * Raises `index` to the next defined index or returns `false`.
*/ */
function raiseIndex() { function raiseIndex() {
index++; index++;
// if queued remove the previous bench // If queued remove the previous bench.
if (queued && index > 0) { if (queued && index > 0) {
shift.call(benches); shift.call(benches);
} }
// if we reached the last index then return `false` // If we reached the last index then return `false`.
return (queued ? benches.length : index < result.length) return (queued ? benches.length : index < result.length)
? index ? index
: (index = false); : (index = false);
} }
// juggle arguments // Juggle arguments.
if (_.isString(name)) { if (_.isString(name)) {
// 2 arguments (array, name) // 2 arguments (array, name).
args = slice.call(arguments, 2); args = slice.call(arguments, 2);
} else { } else {
// 2 arguments (array, options) // 2 arguments (array, options).
options = _.assign(options, name); options = _.assign(options, name);
name = options.name; name = options.name;
args = _.isArray(args = 'args' in options ? options.args : []) ? args : [args]; args = _.isArray(args = 'args' in options ? options.args : []) ? args : [args];
queued = options.queued; queued = options.queued;
} }
// start iterating over the array // Start iterating over the array.
if (raiseIndex() !== false) { if (raiseIndex() !== false) {
// emit "start" event // Emit "start" event.
bench = result[index]; bench = result[index];
eventProps.type = 'start'; eventProps.type = 'start';
eventProps.target = bench; eventProps.target = bench;
options.onStart.call(benches, Event(eventProps)); options.onStart.call(benches, Event(eventProps));
// end early if the suite was aborted in an "onStart" listener // End early if the suite was aborted in an "onStart" listener.
if (benches.aborted && benches.constructor == Suite && name == 'run') { if (benches.aborted && benches.constructor == Suite && name == 'run') {
// emit "cycle" event // Emit "cycle" event.
eventProps.type = 'cycle'; eventProps.type = 'cycle';
options.onCycle.call(benches, Event(eventProps)); options.onCycle.call(benches, Event(eventProps));
// emit "complete" event // Emit "complete" event.
eventProps.type = 'complete'; eventProps.type = 'complete';
options.onComplete.call(benches, Event(eventProps)); options.onComplete.call(benches, Event(eventProps));
} }
// else start // Start method execution.
else { else {
if (isAsync(bench)) { if (isAsync(bench)) {
delay(bench, execute); delay(bench, execute);
} else { } else {
while (execute()) {} while (execute()) {}
} }
} }
} }
return result; return result;
} }
skipping to change at line 1036 skipping to change at line 1018
*/ */
function abortSuite() { function abortSuite() {
var event, var event,
suite = this, suite = this,
resetting = calledBy.resetSuite; resetting = calledBy.resetSuite;
if (suite.running) { if (suite.running) {
event = Event('abort'); event = Event('abort');
suite.emit(event); suite.emit(event);
if (!event.cancelled || resetting) { if (!event.cancelled || resetting) {
// avoid infinite recursion // Avoid infinite recursion.
calledBy.abortSuite = true; calledBy.abortSuite = true;
suite.reset(); suite.reset();
delete calledBy.abortSuite; delete calledBy.abortSuite;
if (!resetting) { if (!resetting) {
suite.aborted = true; suite.aborted = true;
invoke(suite, 'abort'); invoke(suite, 'abort');
} }
} }
} }
skipping to change at line 1110 skipping to change at line 1092
* *
* @name clone * @name clone
* @memberOf Benchmark.Suite * @memberOf Benchmark.Suite
* @param {Object} options Options object to overwrite cloned options. * @param {Object} options Options object to overwrite cloned options.
* @returns {Object} The new suite instance. * @returns {Object} The new suite instance.
*/ */
function cloneSuite(options) { function cloneSuite(options) {
var suite = this, var suite = this,
result = new suite.constructor(_.assign({}, suite.options, options)); result = new suite.constructor(_.assign({}, suite.options, options));
// copy own properties // Copy own properties.
_.forOwn(suite, function(value, key) { _.forOwn(suite, function(value, key) {
if (!_.has(result, key)) { if (!_.has(result, key)) {
result[key] = value && _.isFunction(value.clone) result[key] = value && _.isFunction(value.clone)
? value.clone() ? value.clone()
: cloneDeep(value); : cloneDeep(value);
} }
}); });
return result; return result;
} }
skipping to change at line 1150 skipping to change at line 1132
* @name reset * @name reset
* @memberOf Benchmark.Suite * @memberOf Benchmark.Suite
* @returns {Object} The suite instance. * @returns {Object} The suite instance.
*/ */
function resetSuite() { function resetSuite() {
var event, var event,
suite = this, suite = this,
aborting = calledBy.abortSuite; aborting = calledBy.abortSuite;
if (suite.running && !aborting) { if (suite.running && !aborting) {
// no worries, `resetSuite()` is called within `abortSuite()` // No worries, `resetSuite()` is called within `abortSuite()`.
calledBy.resetSuite = true; calledBy.resetSuite = true;
suite.abort(); suite.abort();
delete calledBy.resetSuite; delete calledBy.resetSuite;
} }
// reset if the state has changed // Reset if the state has changed.
else if ((suite.aborted || suite.running) && else if ((suite.aborted || suite.running) &&
(suite.emit(event = Event('reset')), !event.cancelled)) { (suite.emit(event = Event('reset')), !event.cancelled)) {
suite.aborted = suite.running = false; suite.aborted = suite.running = false;
if (!aborting) { if (!aborting) {
invoke(suite, 'reset'); invoke(suite, 'reset');
} }
} }
return suite; return suite;
} }
skipping to change at line 1356 skipping to change at line 1338
*/ */
function abort() { function abort() {
var event, var event,
bench = this, bench = this,
resetting = calledBy.reset; resetting = calledBy.reset;
if (bench.running) { if (bench.running) {
event = Event('abort'); event = Event('abort');
bench.emit(event); bench.emit(event);
if (!event.cancelled || resetting) { if (!event.cancelled || resetting) {
// avoid infinite recursion // Avoid infinite recursion.
calledBy.abort = true; calledBy.abort = true;
bench.reset(); bench.reset();
delete calledBy.abort; delete calledBy.abort;
if (support.timeout) { if (support.timeout) {
clearTimeout(bench._timerId); clearTimeout(bench._timerId);
delete bench._timerId; delete bench._timerId;
} }
if (!resetting) { if (!resetting) {
bench.aborted = true; bench.aborted = true;
skipping to change at line 1390 skipping to change at line 1372
* @example * @example
* *
* var bizarro = bench.clone({ * var bizarro = bench.clone({
* 'name': 'doppelganger' * 'name': 'doppelganger'
* }); * });
*/ */
function clone(options) { function clone(options) {
var bench = this, var bench = this,
result = new bench.constructor(_.assign({}, bench, options)); result = new bench.constructor(_.assign({}, bench, options));
// correct the `options` object // Correct the `options` object.
result.options = _.assign({}, cloneDeep(bench.options), cloneDeep(options) ); result.options = _.assign({}, cloneDeep(bench.options), cloneDeep(options) );
// copy own custom properties // Copy own custom properties.
_.forOwn(bench, function(value, key) { _.forOwn(bench, function(value, key) {
if (!_.has(result, key)) { if (!_.has(result, key)) {
result[key] = cloneDeep(value); result[key] = cloneDeep(value);
} }
}); });
return result; return result;
} }
/** /**
* Determines if a benchmark is faster than another. * Determines if a benchmark is faster than another.
* *
* @memberOf Benchmark * @memberOf Benchmark
* @param {Object} other The benchmark to compare. * @param {Object} other The benchmark to compare.
* @returns {number} Returns `-1` if slower, `1` if faster, and `0` if indet erminate. * @returns {number} Returns `-1` if slower, `1` if faster, and `0` if indet erminate.
*/ */
function compare(other) { function compare(other) {
var bench = this; var bench = this;
// exit early if comparing the same benchmark // Exit early if comparing the same benchmark.
if (bench == other) { if (bench == other) {
return 0; return 0;
} }
var critical, var critical,
zStat, zStat,
sample1 = bench.stats.sample, sample1 = bench.stats.sample,
sample2 = other.stats.sample, sample2 = other.stats.sample,
size1 = sample1.length, size1 = sample1.length,
size2 = sample2.length, size2 = sample2.length,
maxSize = max(size1, size2), maxSize = max(size1, size2),
skipping to change at line 1444 skipping to change at line 1426
function getU(sampleA, sampleB) { function getU(sampleA, sampleB) {
return _.reduce(sampleA, function(total, xA) { return _.reduce(sampleA, function(total, xA) {
return total + getScore(xA, sampleB); return total + getScore(xA, sampleB);
}, 0); }, 0);
} }
function getZ(u) { function getZ(u) {
return (u - ((size1 * size2) / 2)) / sqrt((size1 * size2 * (size1 + size 2 + 1)) / 12); return (u - ((size1 * size2) / 2)) / sqrt((size1 * size2 * (size1 + size 2 + 1)) / 12);
} }
// reject the null hyphothesis the two samples come from the // Reject the null hypothesis the two samples come from the
// same population (i.e. have the same median) if... // same population (i.e. have the same median) if...
if (size1 + size2 > 30) { if (size1 + size2 > 30) {
// ...the z-stat is greater than 1.96 or less than -1.96 // ...the z-stat is greater than 1.96 or less than -1.96
// http://www.statisticslectures.com/topics/mannwhitneyu/ // http://www.statisticslectures.com/topics/mannwhitneyu/
zStat = getZ(u); zStat = getZ(u);
return abs(zStat) > 1.96 ? (u == u1 ? 1 : -1) : 0; return abs(zStat) > 1.96 ? (u == u1 ? 1 : -1) : 0;
} }
// ...the U value is less than or equal the critical U value // ...the U value is less than or equal the critical U value.
critical = maxSize < 5 || minSize < 3 ? 0 : uTable[maxSize][minSize - 3]; critical = maxSize < 5 || minSize < 3 ? 0 : uTable[maxSize][minSize - 3];
return u <= critical ? (u == u1 ? 1 : -1) : 0; return u <= critical ? (u == u1 ? 1 : -1) : 0;
} }
/** /**
* Reset properties and abort if running. * Reset properties and abort if running.
* *
* @memberOf Benchmark * @memberOf Benchmark
* @returns {Object} The benchmark instance. * @returns {Object} The benchmark instance.
*/ */
function reset() { function reset() {
var bench = this; var bench = this;
if (bench.running && !calledBy.abort) { if (bench.running && !calledBy.abort) {
// no worries, `reset()` is called within `abort()` // No worries, `reset()` is called within `abort()`.
calledBy.reset = true; calledBy.reset = true;
bench.abort(); bench.abort();
delete calledBy.reset; delete calledBy.reset;
return bench; return bench;
} }
var event, var event,
index = 0, index = 0,
changes = [], changes = [],
queue = []; queue = [];
// a non-recursive solution to check if properties have changed // A non-recursive solution to check if properties have changed.
// http://www.jslab.dk/articles/non.recursive.preorder.traversal.part4 // For more information see http://www.jslab.dk/articles/non.recursive.pre
order.traversal.part4.
var data = { var data = {
'destination': bench, 'destination': bench,
'source': _.assign({}, cloneDeep(bench.constructor.prototype), cloneDeep (bench.options)) 'source': _.assign({}, cloneDeep(bench.constructor.prototype), cloneDeep (bench.options))
}; };
do { do {
_.forOwn(data.source, function(value, key) { _.forOwn(data.source, function(value, key) {
var changed, var changed,
destination = data.destination, destination = data.destination,
currValue = destination[key]; currValue = destination[key];
// skip pseudo private properties like `_timerId` which could be a // Skip pseudo private properties like `_timerId` which could be a
// Java object in environments like RingoJS // Java object in environments like RingoJS.
if (key.charAt(0) == '_') { if (key.charAt(0) == '_') {
return; return;
} }
if (value && typeof value == 'object') { if (value && typeof value == 'object') {
if (_.isArray(value)) { if (_.isArray(value)) {
// check if an array value has changed to a non-array value // Check if an array value has changed to a non-array value.
if (!_.isArray(currValue)) { if (!_.isArray(currValue)) {
changed = currValue = []; changed = currValue = [];
} }
// or has changed its length // Check if an array has changed its length.
if (currValue.length != value.length) { if (currValue.length != value.length) {
changed = currValue = currValue.slice(0, value.length); changed = currValue = currValue.slice(0, value.length);
currValue.length = value.length; currValue.length = value.length;
} }
} }
// check if an object has changed to a non-object value // Check if an object has changed to a non-object value.
else if (!currValue || typeof currValue != 'object') { else if (!currValue || typeof currValue != 'object') {
changed = currValue = {}; changed = currValue = {};
} }
// register a changed object // Register a changed object.
if (changed) { if (changed) {
changes.push({ 'destination': destination, 'key': key, 'value': cu rrValue }); changes.push({ 'destination': destination, 'key': key, 'value': cu rrValue });
} }
queue.push({ 'destination': currValue, 'source': value }); queue.push({ 'destination': currValue, 'source': value });
} }
// register a changed primitive // Register a changed primitive.
else if (value !== currValue && !(value == null || _.isFunction(value) )) { else if (value !== currValue && !(value == null || _.isFunction(value) )) {
changes.push({ 'destination': destination, 'key': key, 'value': valu e }); changes.push({ 'destination': destination, 'key': key, 'value': valu e });
} }
}); });
} }
while ((data = queue[index++])); while ((data = queue[index++]));
// if changed emit the `reset` event and if it isn't cancelled reset the b enchmark // If changed emit the `reset` event and if it isn't cancelled reset the b enchmark.
if (changes.length && (bench.emit(event = Event('reset')), !event.cancelle d)) { if (changes.length && (bench.emit(event = Event('reset')), !event.cancelle d)) {
_.each(changes, function(data) { _.each(changes, function(data) {
data.destination[data.key] = data.value; data.destination[data.key] = data.value;
}); });
} }
return bench; return bench;
} }
/** /**
* Displays relevant benchmark information when coerced to a string. * Displays relevant benchmark information when coerced to a string.
skipping to change at line 1548 skipping to change at line 1530
* @memberOf Benchmark * @memberOf Benchmark
* @returns {string} A string representation of the benchmark instance. * @returns {string} A string representation of the benchmark instance.
*/ */
function toStringBench() { function toStringBench() {
var bench = this, var bench = this,
error = bench.error, error = bench.error,
hz = bench.hz, hz = bench.hz,
id = bench.id, id = bench.id,
stats = bench.stats, stats = bench.stats,
size = stats.sample.length, size = stats.sample.length,
pm = support.java ? '+/-' : '\xb1', pm = '\xb1',
result = bench.name || (_.isNaN(id) ? id : '<Test #' + id + '>'); result = bench.name || (_.isNaN(id) ? id : '<Test #' + id + '>');
if (error) { if (error) {
result += ': ' + join(error); result += ': ' + join(error);
} else { } else {
result += ' x ' + formatNumber(hz.toFixed(hz < 100 ? 2 : 0)) + ' ops/sec ' + pm + result += ' x ' + formatNumber(hz.toFixed(hz < 100 ? 2 : 0)) + ' ops/sec ' + pm +
stats.rme.toFixed(2) + '% (' + size + ' run' + (size == 1 ? '' : 's') + ' sampled)'; stats.rme.toFixed(2) + '% (' + size + ' run' + (size == 1 ? '' : 's') + ' sampled)';
} }
return result; return result;
} }
skipping to change at line 1570 skipping to change at line 1552
/*------------------------------------------------------------------------*/ /*------------------------------------------------------------------------*/
/** /**
* Clocks the time taken to execute a test per cycle (secs). * Clocks the time taken to execute a test per cycle (secs).
* *
* @private * @private
* @param {Object} bench The benchmark instance. * @param {Object} bench The benchmark instance.
* @returns {number} The time taken. * @returns {number} The time taken.
*/ */
function clock() { function clock() {
var applet, var options = Benchmark.options,
options = Benchmark.options,
templateData = {}, templateData = {},
timers = [{ 'ns': timer.ns, 'res': max(0.0015, getRes('ms')), 'unit': 'ms' }]; timers = [{ 'ns': timer.ns, 'res': max(0.0015, getRes('ms')), 'unit': 'ms' }];
// lazy define for hi-res timers // Lazy define for hi-res timers.
clock = function(clone) { clock = function(clone) {
var deferred; var deferred;
if (clone instanceof Deferred) { if (clone instanceof Deferred) {
deferred = clone; deferred = clone;
clone = deferred.benchmark; clone = deferred.benchmark;
} }
var bench = clone._original, var bench = clone._original,
stringable = isStringable(bench.fn), stringable = isStringable(bench.fn),
count = bench.count = clone.count, count = bench.count = clone.count,
decompilable = stringable || (support.decompilation && (clone.setup !== _.noop || clone.teardown !== _.noop)), decompilable = stringable || (support.decompilation && (clone.setup !== _.noop || clone.teardown !== _.noop)),
id = bench.id, id = bench.id,
name = bench.name || (typeof id == 'number' ? '<Test #' + id + '>' : id), name = bench.name || (typeof id == 'number' ? '<Test #' + id + '>' : id),
result = 0; result = 0;
// init `minTime` if needed // Init `minTime` if needed.
clone.minTime = bench.minTime || (bench.minTime = bench.options.minTime = options.minTime); clone.minTime = bench.minTime || (bench.minTime = bench.options.minTime = options.minTime);
// repair nanosecond timer
// (some Chrome builds erase the `ns` variable after millions of executi
ons)
if (applet) {
try {
timer.ns.nanoTime();
} catch(e) {
// use non-element to avoid issues with libs that augment them
timer.ns = new applet.Packages.nano;
}
}
// Compile in setup/teardown functions and the test loop. // Compile in setup/teardown functions and the test loop.
// Create a new compiled test, instead of using the cached `bench.compil ed`, // Create a new compiled test, instead of using the cached `bench.compil ed`,
// to avoid potential engine optimizations enabled over the life of the test. // to avoid potential engine optimizations enabled over the life of the test.
var funcBody = deferred var funcBody = deferred
? 'var d#=this,${fnArg}=d#,m#=d#.benchmark._original,f#=m#.fn,su#=m#.s etup,td#=m#.teardown;' + ? 'var d#=this,${fnArg}=d#,m#=d#.benchmark._original,f#=m#.fn,su#=m#.s etup,td#=m#.teardown;' +
// when `deferred.cycles` is `0` then... // When `deferred.cycles` is `0` then...
'if(!d#.cycles){' + 'if(!d#.cycles){' +
// set `deferred.fn` // set `deferred.fn`,
'd#.fn=function(){var ${fnArg}=d#;if(typeof f#=="function"){try{${fn }\n}catch(e#){f#(d#)}}else{${fn}\n}};' + 'd#.fn=function(){var ${fnArg}=d#;if(typeof f#=="function"){try{${fn }\n}catch(e#){f#(d#)}}else{${fn}\n}};' +
// set `deferred.teardown` // set `deferred.teardown`,
'd#.teardown=function(){d#.cycles=0;if(typeof td#=="function"){try{$ {teardown}\n}catch(e#){td#()}}else{${teardown}\n}};' + 'd#.teardown=function(){d#.cycles=0;if(typeof td#=="function"){try{$ {teardown}\n}catch(e#){td#()}}else{${teardown}\n}};' +
// execute the benchmark's `setup` // execute the benchmark's `setup`,
'if(typeof su#=="function"){try{${setup}\n}catch(e#){su#()}}else{${s etup}\n};' + 'if(typeof su#=="function"){try{${setup}\n}catch(e#){su#()}}else{${s etup}\n};' +
// start timer // start timer,
't#.start(d#);' + 't#.start(d#);' +
// execute `deferred.fn` and return a dummy object // and then execute `deferred.fn` and return a dummy object.
'}d#.fn();return{uid:"${uid}"}' '}d#.fn();return{uid:"${uid}"}'
: 'var r#,s#,m#=this,f#=m#.fn,i#=m#.count,n#=t#.ns;${setup}\n${begin}; ' + : 'var r#,s#,m#=this,f#=m#.fn,i#=m#.count,n#=t#.ns;${setup}\n${begin}; ' +
'while(i#--){${fn}\n}${end};${teardown}\nreturn{elapsed:r#,uid:"${ui d}"}'; 'while(i#--){${fn}\n}${end};${teardown}\nreturn{elapsed:r#,uid:"${ui d}"}';
var compiled = bench.compiled = clone.compiled = createCompiled(bench, d ecompilable, deferred, funcBody), var compiled = bench.compiled = clone.compiled = createCompiled(bench, d ecompilable, deferred, funcBody),
isEmpty = !(templateData.fn || stringable); isEmpty = !(templateData.fn || stringable);
try { try {
if (isEmpty) { if (isEmpty) {
// Firefox may remove dead code from `Function#toString` results // Firefox may remove dead code from `Function#toString` results.
// http://bugzil.la/536085 // For more information see http://bugzil.la/536085.
throw new Error('The test "' + name + '" is empty. This may be the r esult of dead code removal.'); throw new Error('The test "' + name + '" is empty. This may be the r esult of dead code removal.');
} }
else if (!deferred) { else if (!deferred) {
// pretest to determine if compiled code exits early, usually by a // Pretest to determine if compiled code exits early, usually by a
// rogue `return` statement, by checking for a return object with th // rogue `return` statement, by checking for a return object with th
e uid e uid.
bench.count = 1; bench.count = 1;
compiled = decompilable && (compiled.call(bench, context, timer) || {}).uid == templateData.uid && compiled; compiled = decompilable && (compiled.call(bench, context, timer) || {}).uid == templateData.uid && compiled;
bench.count = count; bench.count = count;
} }
} catch(e) { } catch(e) {
compiled = null; compiled = null;
clone.error = e || new Error(String(e)); clone.error = e || new Error(String(e));
bench.count = count; bench.count = count;
} }
// fallback when a test exits early or errors during pretest // Fallback when a test exits early or errors during pretest.
if (!compiled && !deferred && !isEmpty) { if (!compiled && !deferred && !isEmpty) {
funcBody = ( funcBody = (
stringable || (decompilable && !clone.error) stringable || (decompilable && !clone.error)
? 'function f#(){${fn}\n}var r#,s#,m#=this,i#=m#.count' ? 'function f#(){${fn}\n}var r#,s#,m#=this,i#=m#.count'
: 'var r#,s#,m#=this,f#=m#.fn,i#=m#.count' : 'var r#,s#,m#=this,f#=m#.fn,i#=m#.count'
) + ) +
',n#=t#.ns;${setup}\n${begin};m#.f#=f#;while(i#--){m#.f#()}${end};' + ',n#=t#.ns;${setup}\n${begin};m#.f#=f#;while(i#--){m#.f#()}${end};' +
'delete m#.f#;${teardown}\nreturn{elapsed:r#}'; 'delete m#.f#;${teardown}\nreturn{elapsed:r#}';
compiled = createCompiled(bench, decompilable, deferred, funcBody); compiled = createCompiled(bench, decompilable, deferred, funcBody);
try { try {
// pretest one more time to check for errors // Pretest one more time to check for errors.
bench.count = 1; bench.count = 1;
compiled.call(bench, context, timer); compiled.call(bench, context, timer);
bench.count = count; bench.count = count;
delete clone.error; delete clone.error;
} }
catch(e) { catch(e) {
bench.count = count; bench.count = count;
if (!clone.error) { if (!clone.error) {
clone.error = e || new Error(String(e)); clone.error = e || new Error(String(e));
} }
} }
} }
// if no errors run the full test loop // If no errors run the full test loop.
if (!clone.error) { if (!clone.error) {
compiled = bench.compiled = clone.compiled = createCompiled(bench, dec ompilable, deferred, funcBody); compiled = bench.compiled = clone.compiled = createCompiled(bench, dec ompilable, deferred, funcBody);
result = compiled.call(deferred || bench, context, timer).elapsed; result = compiled.call(deferred || bench, context, timer).elapsed;
} }
return result; return result;
}; };
/*----------------------------------------------------------------------*/ /*----------------------------------------------------------------------*/
/** /**
skipping to change at line 1698 skipping to change at line 1669
templateData.uid = uid + uidCounter++; templateData.uid = uid + uidCounter++;
_.assign(templateData, { _.assign(templateData, {
'setup': decompilable ? getSource(bench.setup) : interpolate('m#.setup ()'), 'setup': decompilable ? getSource(bench.setup) : interpolate('m#.setup ()'),
'fn': decompilable ? getSource(fn) : interpolate('m#.fn(' + fnArg + ') '), 'fn': decompilable ? getSource(fn) : interpolate('m#.fn(' + fnArg + ') '),
'fnArg': fnArg, 'fnArg': fnArg,
'teardown': decompilable ? getSource(bench.teardown) : interpolate('m# .teardown()') 'teardown': decompilable ? getSource(bench.teardown) : interpolate('m# .teardown()')
}); });
// use API of chosen timer // Use API of chosen timer.
if (timer.unit == 'ns') { if (timer.unit == 'ns') {
if (timer.ns.nanoTime) { _.assign(templateData, {
_.assign(templateData, { 'begin': interpolate('s#=n#()'),
'begin': interpolate('s#=n#.nanoTime()'), 'end': interpolate('r#=n#(s#);r#=r#[0]+(r#[1]/1e9)')
'end': interpolate('r#=(n#.nanoTime()-s#)/1e9') });
});
} else {
_.assign(templateData, {
'begin': interpolate('s#=n#()'),
'end': interpolate('r#=n#(s#);r#=r#[0]+(r#[1]/1e9)')
});
}
} }
else if (timer.unit == 'us') { else if (timer.unit == 'us') {
if (timer.ns.stop) { if (timer.ns.stop) {
_.assign(templateData, { _.assign(templateData, {
'begin': interpolate('s#=n#.start()'), 'begin': interpolate('s#=n#.start()'),
'end': interpolate('r#=n#.microseconds()/1e6') 'end': interpolate('r#=n#.microseconds()/1e6')
}); });
} else { } else {
_.assign(templateData, { _.assign(templateData, {
'begin': interpolate('s#=n#()'), 'begin': interpolate('s#=n#()'),
skipping to change at line 1737 skipping to change at line 1701
'begin': interpolate('s#=n#.now()'), 'begin': interpolate('s#=n#.now()'),
'end': interpolate('r#=(n#.now()-s#)/1e3') 'end': interpolate('r#=(n#.now()-s#)/1e3')
}); });
} }
else { else {
_.assign(templateData, { _.assign(templateData, {
'begin': interpolate('s#=new n#().getTime()'), 'begin': interpolate('s#=new n#().getTime()'),
'end': interpolate('r#=(new n#().getTime()-s#)/1e3') 'end': interpolate('r#=(new n#().getTime()-s#)/1e3')
}); });
} }
// define `timer` methods // Define `timer` methods.
timer.start = createFunction( timer.start = createFunction(
interpolate('o#'), interpolate('o#'),
interpolate('var n#=this.ns,${begin};o#.elapsed=0;o#.timeStamp=s#') interpolate('var n#=this.ns,${begin};o#.elapsed=0;o#.timeStamp=s#')
); );
timer.stop = createFunction( timer.stop = createFunction(
interpolate('o#'), interpolate('o#'),
interpolate('var n#=this.ns,s#=o#.timeStamp,${end};o#.elapsed=r#') interpolate('var n#=this.ns,s#=o#.timeStamp,${end};o#.elapsed=r#')
); );
// create compiled test // Create compiled test.
return createFunction( return createFunction(
interpolate('window,t#'), interpolate('window,t#'),
'var global = window, clearTimeout = global.clearTimeout, setTimeout = global.setTimeout;\n' + 'var global = window, clearTimeout = global.clearTimeout, setTimeout = global.setTimeout;\n' +
interpolate(body) interpolate(body)
); );
} }
/** /**
* Gets the current timer's minimum resolution (secs). * Gets the current timer's minimum resolution (secs).
*/ */
function getRes(unit) { function getRes(unit) {
var measured, var measured,
begin, begin,
count = 30, count = 30,
divisor = 1e3, divisor = 1e3,
ns = timer.ns, ns = timer.ns,
sample = []; sample = [];
// get average smallest measurable time // Get average smallest measurable time.
while (count--) { while (count--) {
if (unit == 'us') { if (unit == 'us') {
divisor = 1e6; divisor = 1e6;
if (ns.stop) { if (ns.stop) {
ns.start(); ns.start();
while (!(measured = ns.microseconds())) {} while (!(measured = ns.microseconds())) {}
} else { } else {
begin = ns(); begin = ns();
while (!(measured = ns() - begin)) {} while (!(measured = ns() - begin)) {}
} }
} }
else if (unit == 'ns') { else if (unit == 'ns') {
divisor = 1e9; divisor = 1e9;
if (ns.nanoTime) { begin = (begin = ns())[0] + (begin[1] / divisor);
begin = ns.nanoTime(); while (!(measured = ((measured = ns())[0] + (measured[1] / divisor))
while (!(measured = ns.nanoTime() - begin)) {} - begin)) {}
} else { divisor = 1;
begin = (begin = ns())[0] + (begin[1] / divisor);
while (!(measured = ((measured = ns())[0] + (measured[1] / divisor
)) - begin)) {}
divisor = 1;
}
} }
else if (ns.now) { else if (ns.now) {
begin = ns.now(); begin = ns.now();
while (!(measured = ns.now() - begin)) {} while (!(measured = ns.now() - begin)) {}
} }
else { else {
begin = new ns().getTime(); begin = new ns().getTime();
while (!(measured = new ns().getTime() - begin)) {} while (!(measured = new ns().getTime() - begin)) {}
} }
// check for broken timers (`nanoTime` may have issues) // Check for broken timers.
// http://alivebutsleepy.srnet.cz/unreliable-system-nanotime/
if (measured > 0) { if (measured > 0) {
sample.push(measured); sample.push(measured);
} else { } else {
sample.push(Infinity); sample.push(Infinity);
break; break;
} }
} }
// convert to seconds // Convert to seconds.
return getMean(sample) / divisor; return getMean(sample) / divisor;
} }
/** /**
* Interpolates a given template string. * Interpolates a given template string.
*/ */
function interpolate(string) { function interpolate(string) {
// replaces all occurrences of `#` with a unique number and template tok ens with content // Replaces all occurrences of `#` with a unique number and template tok ens with content.
return _.template(string.replace(/\#/g, /\d+/.exec(templateData.uid)))(t emplateData); return _.template(string.replace(/\#/g, /\d+/.exec(templateData.uid)))(t emplateData);
} }
/*----------------------------------------------------------------------*/ /*----------------------------------------------------------------------*/
// detect nanosecond support from a Java applet // Detect Chrome's microsecond timer:
_.each(doc && doc.applets || [], function(element) {
return !(timer.ns = applet = 'nanoTime' in element && element);
});
// check type in case Safari returns an object instead of a number
try {
if (typeof timer.ns.nanoTime() == 'number') {
timers.push({ 'ns': timer.ns, 'res': getRes('ns'), 'unit': 'ns' });
}
} catch(e) {}
// detect Chrome's microsecond timer:
// enable benchmarking via the --enable-benchmarking command // enable benchmarking via the --enable-benchmarking command
// line switch in at least Chrome 7 to use chrome.Interval // line switch in at least Chrome 7 to use chrome.Interval
try { try {
if ((timer.ns = new (context.chrome || context.chromium).Interval)) { if ((timer.ns = new (context.chrome || context.chromium).Interval)) {
timers.push({ 'ns': timer.ns, 'res': getRes('us'), 'unit': 'us' }); timers.push({ 'ns': timer.ns, 'res': getRes('us'), 'unit': 'us' });
} }
} catch(e) {} } catch(e) {}
// detect Node.js's nanosecond resolution timer available in Node.js >= 0. 8 // Detect Node.js's nanosecond resolution timer available in Node.js >= 0. 8.
if (processObject && typeof (timer.ns = processObject.hrtime) == 'function ') { if (processObject && typeof (timer.ns = processObject.hrtime) == 'function ') {
timers.push({ 'ns': timer.ns, 'res': getRes('ns'), 'unit': 'ns' }); timers.push({ 'ns': timer.ns, 'res': getRes('ns'), 'unit': 'ns' });
} }
// detect Wade Simmons' Node.js `microtime` module // Detect Wade Simmons' Node.js `microtime` module.
if (microtimeObject && typeof (timer.ns = microtimeObject.now) == 'functio n') { if (microtimeObject && typeof (timer.ns = microtimeObject.now) == 'functio n') {
timers.push({ 'ns': timer.ns, 'res': getRes('us'), 'unit': 'us' }); timers.push({ 'ns': timer.ns, 'res': getRes('us'), 'unit': 'us' });
} }
// pick timer with highest resolution // Pick timer with highest resolution.
timer = _.min(timers, 'res'); timer = (_.minBy || _.min)(timers, 'res');
// remove unused applet // Error if there are no working timers.
if (timer.unit != 'ns' && applet) {
applet = destroyElement(applet);
}
// error if there are no working timers
if (timer.res == Infinity) { if (timer.res == Infinity) {
throw new Error('Benchmark.js was unable to find a working timer.'); throw new Error('Benchmark.js was unable to find a working timer.');
} }
// resolve time span required to achieve a percent uncertainty of at most // Resolve time span required to achieve a percent uncertainty of at most
1% 1%.
// http://spiff.rit.edu/classes/phys273/uncert/uncert.html // For more information see http://spiff.rit.edu/classes/phys273/uncert/un
cert.html.
options.minTime || (options.minTime = max(timer.res / 2 / 0.01, 0.05)); options.minTime || (options.minTime = max(timer.res / 2 / 0.01, 0.05));
return clock.apply(null, arguments); return clock.apply(null, arguments);
} }
/*------------------------------------------------------------------------*/ /*------------------------------------------------------------------------*/
/** /**
* Computes stats on benchmark results. * Computes stats on benchmark results.
* *
* @private * @private
skipping to change at line 1910 skipping to change at line 1852
/** /**
* Updates the clone/original benchmarks to keep their data in sync. * Updates the clone/original benchmarks to keep their data in sync.
*/ */
function update(event) { function update(event) {
var clone = this, var clone = this,
type = event.type; type = event.type;
if (bench.running) { if (bench.running) {
if (type == 'start') { if (type == 'start') {
// Note: `clone.minTime` prop is inited in `clock()` // Note: `clone.minTime` prop is inited in `clock()`.
clone.count = bench.initCount; clone.count = bench.initCount;
} }
else { else {
if (type == 'error') { if (type == 'error') {
bench.error = clone.error; bench.error = clone.error;
} }
if (type == 'abort') { if (type == 'abort') {
bench.abort(); bench.abort();
bench.emit('cycle'); bench.emit('cycle');
} else { } else {
event.currentTarget = event.target = bench; event.currentTarget = event.target = bench;
bench.emit(event); bench.emit(event);
} }
} }
} else if (bench.aborted) { } else if (bench.aborted) {
// clear abort listeners to avoid triggering bench's abort/cycle again // Clear abort listeners to avoid triggering bench's abort/cycle again .
clone.events.abort.length = 0; clone.events.abort.length = 0;
clone.abort(); clone.abort();
} }
} }
/** /**
* Determines if more clones should be queued or if cycling should stop. * Determines if more clones should be queued or if cycling should stop.
*/ */
function evaluate(event) { function evaluate(event) {
var critical, var critical,
skipping to change at line 1952 skipping to change at line 1894
sem, sem,
variance, variance,
clone = event.target, clone = event.target,
done = bench.aborted, done = bench.aborted,
now = _.now(), now = _.now(),
size = sample.push(clone.times.period), size = sample.push(clone.times.period),
maxedOut = size >= minSamples && (elapsed += now - clone.times.timeS tamp) / 1e3 > bench.maxTime, maxedOut = size >= minSamples && (elapsed += now - clone.times.timeS tamp) / 1e3 > bench.maxTime,
times = bench.times, times = bench.times,
varOf = function(sum, x) { return sum + pow(x - mean, 2); }; varOf = function(sum, x) { return sum + pow(x - mean, 2); };
// exit early for aborted or unclockable tests // Exit early for aborted or unclockable tests.
if (done || clone.hz == Infinity) { if (done || clone.hz == Infinity) {
maxedOut = !(size = sample.length = queue.length = 0); maxedOut = !(size = sample.length = queue.length = 0);
} }
if (!done) { if (!done) {
// sample mean (estimate of the population mean) // Compute the sample mean (estimate of the population mean).
mean = getMean(sample); mean = getMean(sample);
// sample variance (estimate of the population variance) // Compute the sample variance (estimate of the population variance).
variance = _.reduce(sample, varOf, 0) / (size - 1) || 0; variance = _.reduce(sample, varOf, 0) / (size - 1) || 0;
// sample standard deviation (estimate of the population standard devi ation) // Compute the sample standard deviation (estimate of the population s tandard deviation).
sd = sqrt(variance); sd = sqrt(variance);
// standard error of the mean (a.k.a. the standard deviation of the sa mpling distribution of the sample mean) // Compute the standard error of the mean (a.k.a. the standard deviati on of the sampling distribution of the sample mean).
sem = sd / sqrt(size); sem = sd / sqrt(size);
// degrees of freedom // Compute the degrees of freedom.
df = size - 1; df = size - 1;
// critical value // Compute the critical value.
critical = tTable[Math.round(df) || 1] || tTable.infinity; critical = tTable[Math.round(df) || 1] || tTable.infinity;
// margin of error // Compute the margin of error.
moe = sem * critical; moe = sem * critical;
// relative margin of error // Compute the relative margin of error.
rme = (moe / mean) * 100 || 0; rme = (moe / mean) * 100 || 0;
_.assign(bench.stats, { _.assign(bench.stats, {
'deviation': sd, 'deviation': sd,
'mean': mean, 'mean': mean,
'moe': moe, 'moe': moe,
'rme': rme, 'rme': rme,
'sem': sem, 'sem': sem,
'variance': variance 'variance': variance
}); });
// Abort the cycle loop when the minimum sample size has been collecte d // Abort the cycle loop when the minimum sample size has been collecte d
// and the elapsed time exceeds the maximum time allowed per benchmark . // and the elapsed time exceeds the maximum time allowed per benchmark .
// We don't count cycle delays toward the max time because delays may be // We don't count cycle delays toward the max time because delays may be
// increased by browsers that clamp timeouts for inactive tabs. // increased by browsers that clamp timeouts for inactive tabs. For mo
// https://developer.mozilla.org/en/window.setTimeout#Inactive_tabs re
// information see https://developer.mozilla.org/en/window.setTimeout#
Inactive_tabs.
if (maxedOut) { if (maxedOut) {
// reset the `initCount` in case the benchmark is rerun // Reset the `initCount` in case the benchmark is rerun.
bench.initCount = initCount; bench.initCount = initCount;
bench.running = false; bench.running = false;
done = true; done = true;
times.elapsed = (now - times.timeStamp) / 1e3; times.elapsed = (now - times.timeStamp) / 1e3;
} }
if (bench.hz != Infinity) { if (bench.hz != Infinity) {
bench.hz = 1 / mean; bench.hz = 1 / mean;
times.cycle = mean * bench.count; times.cycle = mean * bench.count;
times.period = mean; times.period = mean;
} }
} }
// if time permits, increase sample size to reduce the margin of error // If time permits, increase sample size to reduce the margin of error.
if (queue.length < 2 && !maxedOut) { if (queue.length < 2 && !maxedOut) {
enqueue(); enqueue();
} }
// abort the `invoke` cycle when done // Abort the `invoke` cycle when done.
event.aborted = done; event.aborted = done;
} }
// init queue and begin // Init queue and begin.
enqueue(); enqueue();
invoke(queue, { invoke(queue, {
'name': 'run', 'name': 'run',
'args': { 'async': async }, 'args': { 'async': async },
'queued': true, 'queued': true,
'onCycle': evaluate, 'onCycle': evaluate,
'onComplete': function() { bench.emit('complete'); } 'onComplete': function() { bench.emit('complete'); }
}); });
} }
skipping to change at line 2050 skipping to change at line 1992
cycles, cycles,
divisor, divisor,
event, event,
minTime, minTime,
period, period,
async = options.async, async = options.async,
bench = clone._original, bench = clone._original,
count = clone.count, count = clone.count,
times = clone.times; times = clone.times;
// continue, if not aborted between cycles // Continue, if not aborted between cycles.
if (clone.running) { if (clone.running) {
// `minTime` is set to `Benchmark.options.minTime` in `clock()` // `minTime` is set to `Benchmark.options.minTime` in `clock()`.
cycles = ++clone.cycles; cycles = ++clone.cycles;
clocked = deferred ? deferred.elapsed : clock(clone); clocked = deferred ? deferred.elapsed : clock(clone);
minTime = clone.minTime; minTime = clone.minTime;
if (cycles > bench.cycles) { if (cycles > bench.cycles) {
bench.cycles = cycles; bench.cycles = cycles;
} }
if (clone.error) { if (clone.error) {
event = Event('error'); event = Event('error');
event.message = clone.error; event.message = clone.error;
clone.emit(event); clone.emit(event);
if (!event.cancelled) { if (!event.cancelled) {
clone.abort(); clone.abort();
} }
} }
} }
// continue, if not errored // Continue, if not errored.
if (clone.running) { if (clone.running) {
// time taken to complete last test cycle // Compute the time taken to complete last test cycle.
bench.times.cycle = times.cycle = clocked; bench.times.cycle = times.cycle = clocked;
// seconds per operation // Compute the seconds per operation.
period = bench.times.period = times.period = clocked / count; period = bench.times.period = times.period = clocked / count;
// ops per second // Compute the ops per second.
bench.hz = clone.hz = 1 / period; bench.hz = clone.hz = 1 / period;
// avoid working our way up to this next time // Avoid working our way up to this next time.
bench.initCount = clone.initCount = count; bench.initCount = clone.initCount = count;
// do we need to do another cycle? // Do we need to do another cycle?
clone.running = clocked < minTime; clone.running = clocked < minTime;
if (clone.running) { if (clone.running) {
// tests may clock at `0` when `initCount` is a small number, // Tests may clock at `0` when `initCount` is a small number,
// to avoid that we set its count to something a bit higher // to avoid that we set its count to something a bit higher.
if (!clocked && (divisor = divisors[clone.cycles]) != null) { if (!clocked && (divisor = divisors[clone.cycles]) != null) {
count = floor(4e6 / divisor); count = floor(4e6 / divisor);
} }
// calculate how many more iterations it will take to achive the `minT ime` // Calculate how many more iterations it will take to achieve the `min Time`.
if (count <= clone.count) { if (count <= clone.count) {
count += Math.ceil((minTime - clocked) / period); count += Math.ceil((minTime - clocked) / period);
} }
clone.running = count != Infinity; clone.running = count != Infinity;
} }
} }
// should we exit early? // Should we exit early?
event = Event('cycle'); event = Event('cycle');
clone.emit(event); clone.emit(event);
if (event.aborted) { if (event.aborted) {
clone.abort(); clone.abort();
} }
// figure out what to do next // Figure out what to do next.
if (clone.running) { if (clone.running) {
// start a new cycle // Start a new cycle.
clone.count = count; clone.count = count;
if (deferred) { if (deferred) {
clone.compiled.call(deferred, context, timer); clone.compiled.call(deferred, context, timer);
} else if (async) { } else if (async) {
delay(clone, function() { cycle(clone, options); }); delay(clone, function() { cycle(clone, options); });
} else { } else {
cycle(clone); cycle(clone);
} }
} }
else { else {
// fix TraceMonkey bug associated with clock fallbacks // Fix TraceMonkey bug associated with clock fallbacks.
// http://bugzil.la/509069 // For more information see http://bugzil.la/509069.
if (support.browser) { if (support.browser) {
runScript(uid + '=1;delete ' + uid); runScript(uid + '=1;delete ' + uid);
} }
// done // We're done.
clone.emit('complete'); clone.emit('complete');
} }
} }
/*------------------------------------------------------------------------*/ /*------------------------------------------------------------------------*/
/** /**
* Runs the benchmark. * Runs the benchmark.
* *
* @memberOf Benchmark * @memberOf Benchmark
skipping to change at line 2145 skipping to change at line 2087
* // basic usage * // basic usage
* bench.run(); * bench.run();
* *
* // or with options * // or with options
* bench.run({ 'async': true }); * bench.run({ 'async': true });
*/ */
function run(options) { function run(options) {
var bench = this, var bench = this,
event = Event('start'); event = Event('start');
// set `running` to `false` so `reset()` won't call `abort()` // Set `running` to `false` so `reset()` won't call `abort()`.
bench.running = false; bench.running = false;
bench.reset(); bench.reset();
bench.running = true; bench.running = true;
bench.count = bench.initCount; bench.count = bench.initCount;
bench.times.timeStamp = _.now(); bench.times.timeStamp = _.now();
bench.emit(event); bench.emit(event);
if (!event.cancelled) { if (!event.cancelled) {
options = { 'async': ((options = options && options.async) == null ? ben ch.async : options) && support.timeout }; options = { 'async': ((options = options && options.async) == null ? ben ch.async : options) && support.timeout };
// for clones created within `compute()` // For clones created within `compute()`.
if (bench._original) { if (bench._original) {
if (bench.defer) { if (bench.defer) {
Deferred(bench); Deferred(bench);
} else { } else {
cycle(bench, options); cycle(bench, options);
} }
} }
// for original benchmarks // For original benchmarks.
else { else {
compute(bench, options); compute(bench, options);
} }
} }
return bench; return bench;
} }
/*------------------------------------------------------------------------*/ /*------------------------------------------------------------------------*/
// Firefox 1 erroneously defines variable and argument names of functions on // Firefox 1 erroneously defines variable and argument names of functions on
skipping to change at line 2357 skipping to change at line 2299
_.assign(Benchmark, { _.assign(Benchmark, {
'filter': filter, 'filter': filter,
'formatNumber': formatNumber, 'formatNumber': formatNumber,
'invoke': invoke, 'invoke': invoke,
'join': join, 'join': join,
'runInContext': runInContext, 'runInContext': runInContext,
'support': support 'support': support
}); });
// Add lodash methods to Benchmark // Add lodash methods to Benchmark.
_.each(['each', 'forEach', 'forOwn', 'has', 'indexOf', 'map', 'pluck', 'redu ce'], function(methodName) { _.each(['each', 'forEach', 'forOwn', 'has', 'indexOf', 'map', 'pluck', 'redu ce'], function(methodName) {
Benchmark[methodName] = _[methodName]; Benchmark[methodName] = _[methodName];
}); });
/*------------------------------------------------------------------------*/ /*------------------------------------------------------------------------*/
_.assign(Benchmark.prototype, { _.assign(Benchmark.prototype, {
/** /**
* The number of times a test was executed. * The number of times a test was executed.
skipping to change at line 2796 skipping to change at line 2738
'reverse': arrayRef.reverse, 'reverse': arrayRef.reverse,
'shift': shift, 'shift': shift,
'slice': slice, 'slice': slice,
'sort': arrayRef.sort, 'sort': arrayRef.sort,
'splice': arrayRef.splice, 'splice': arrayRef.splice,
'unshift': unshift 'unshift': unshift
}); });
/*------------------------------------------------------------------------*/ /*------------------------------------------------------------------------*/
// expose Deferred, Event, and Suite // Expose Deferred, Event, and Suite.
_.assign(Benchmark, { _.assign(Benchmark, {
'Deferred': Deferred, 'Deferred': Deferred,
'Event': Event, 'Event': Event,
'Suite': Suite 'Suite': Suite
}); });
/*------------------------------------------------------------------------*/ /*------------------------------------------------------------------------*/
// add lodash methods as Suite methods // Add lodash methods as Suite methods.
_.each(['each', 'forEach', 'indexOf', 'map', 'pluck', 'reduce'], function(me thodName) { _.each(['each', 'forEach', 'indexOf', 'map', 'pluck', 'reduce'], function(me thodName) {
var func = _[methodName]; var func = _[methodName];
Suite.prototype[methodName] = function() { Suite.prototype[methodName] = function() {
var args = [this]; var args = [this];
push.apply(args, arguments); push.apply(args, arguments);
return func.apply(_, args); return func.apply(_, args);
}; };
}); });
// avoid array-like object bugs with `Array#shift` and `Array#splice` // Avoid array-like object bugs with `Array#shift` and `Array#splice`
// in Firefox < 10 and IE < 9 // in Firefox < 10 and IE < 9.
if (!_.support.spliceObjects) { _.each(['pop', 'shift', 'splice'], function(methodName) {
_.each(['pop', 'shift', 'splice'], function(methodName) { var func = arrayRef[methodName];
var func = arrayRef[methodName];
Suite.prototype[methodName] = function() {
var value = this,
result = func.apply(value, arguments);
if (value.length === 0) { Suite.prototype[methodName] = function() {
delete value[0]; var value = this,
} result = func.apply(value, arguments);
return result;
}; if (value.length === 0) {
}); delete value[0];
} }
// avoid buggy `Array#unshift` in IE < 8 which doesn't return the new return result;
// length of the array
if (!support.unshiftResult) {
Suite.prototype.unshift = function() {
var value = this;
unshift.apply(value, arguments);
return value.length;
}; };
} });
// Avoid buggy `Array#unshift` in IE < 8 which doesn't return the new
// length of the array.
Suite.prototype.unshift = function() {
var value = this;
unshift.apply(value, arguments);
return value.length;
};
return Benchmark; return Benchmark;
} }
/*--------------------------------------------------------------------------*/ /*--------------------------------------------------------------------------*/
// export Benchmark // Export Benchmark.
// some AMD build optimizers, like r.js, check for condition patterns like the // Some AMD build optimizers, like r.js, check for condition patterns like the
following: following:
if (typeof define == 'function' && typeof define.amd == 'object' && define.amd ) { if (typeof define == 'function' && typeof define.amd == 'object' && define.amd ) {
// define as an anonymous module so, through path mapping, it can be aliased // Define as an anonymous module so, through path mapping, it can be aliased .
define(['lodash', 'platform'], function(_, platform) { define(['lodash', 'platform'], function(_, platform) {
return runInContext({ return runInContext({
'_': _, '_': _,
'platform': platform 'platform': platform
}); });
}); });
} }
else { else {
var Benchmark = runInContext(); var Benchmark = runInContext();
// check for `exports` after `define` in case a build optimizer adds an `exp orts` object // Check for `exports` after `define` in case a build optimizer adds an `exp orts` object.
if (freeExports && freeModule) { if (freeExports && freeModule) {
// in Node.js or RingoJS // Export for Node.js or RingoJS.
if (moduleExports) { if (moduleExports) {
(freeModule.exports = Benchmark).Benchmark = Benchmark; (freeModule.exports = Benchmark).Benchmark = Benchmark;
} }
// in Narwhal or Rhino -require // Export for Rhino with CommonJS support.
else { else {
freeExports.Benchmark = Benchmark; freeExports.Benchmark = Benchmark;
} }
} }
else { else {
// in a browser or Rhino // Export for a browser or Rhino.
root.Benchmark = Benchmark; root.Benchmark = Benchmark;
} }
} }
}.call(this)); }.call(this));
 End of changes. 175 change blocks. 
281 lines changed or deleted 228 lines changed or added

Home  |  About  |  Features  |  All  |  Newest  |  Dox  |  Diffs  |  RSS Feeds  |  Screenshots  |  Comments  |  Imprint  |  Privacy  |  HTTP(S)