Path: blob/trunk/third_party/closure/goog/testing/performancetimer.js
4050 views
/**1* @license2* Copyright The Closure Library Authors.3* SPDX-License-Identifier: Apache-2.04*/56/**7* @fileoverview Performance timer.8*9* {@see goog.testing.benchmark} for an easy way to use this functionality.10*/1112goog.setTestOnly('goog.testing.PerformanceTimer');13goog.provide('goog.testing.PerformanceTimer');14goog.provide('goog.testing.PerformanceTimer.Task');1516goog.require('goog.Thenable');17goog.require('goog.array');18goog.require('goog.async.Deferred');19goog.require('goog.math');20212223/**24* Creates a performance timer that runs test functions a number of times to25* generate timing samples, and provides performance statistics (minimum,26* maximum, average, and standard deviation).27* @param {number=} opt_numSamples Number of times to run the test function;28* defaults to 10.29* @param {number=} opt_timeoutInterval Number of milliseconds after which the30* test is to be aborted; defaults to 5 seconds (5,000ms).31* @constructor32*/33goog.testing.PerformanceTimer = function(opt_numSamples, opt_timeoutInterval) {34'use strict';35/**36* Number of times the test function is to be run; defaults to 10.37* @private {number}38*/39this.numSamples_ = opt_numSamples || 10;4041/**42* Number of milliseconds after which the test is to be aborted; defaults to43* 5,000ms.44* @private {number}45*/46this.timeoutInterval_ = opt_timeoutInterval || 5000;4748/**49* Whether to discard outliers (i.e. the smallest and the largest values)50* from the sample set before computing statistics. Defaults to false.51* @private {boolean}52*/53this.discardOutliers_ = false;54};555657/**58* A function whose subsequent calls differ in milliseconds. Used to calculate59* the start and stop checkpoint times for runs. Note that high performance60* timers do not necessarily return the current time in milliseconds.61* @return {number}62* @private63*/64goog.testing.PerformanceTimer.now_ = function() {65'use strict';66// goog.now is used in DEBUG mode to make the class easier to test.67return !goog.DEBUG && window.performance && window.performance.now ?68window.performance.now() :69goog.now();70};717273/**74* @return {number} The number of times the test function will be run.75*/76goog.testing.PerformanceTimer.prototype.getNumSamples = function() {77'use strict';78return this.numSamples_;79};808182/**83* Sets the number of times the test function will be run.84* @param {number} numSamples Number of times to run the test function.85*/86goog.testing.PerformanceTimer.prototype.setNumSamples = function(numSamples) {87'use strict';88this.numSamples_ = numSamples;89};909192/**93* @return {number} The number of milliseconds after which the test times out.94*/95goog.testing.PerformanceTimer.prototype.getTimeoutInterval = function() {96'use strict';97return this.timeoutInterval_;98};99100101/**102* Sets the number of milliseconds after which the test times out.103* @param {number} timeoutInterval Timeout interval in ms.104*/105goog.testing.PerformanceTimer.prototype.setTimeoutInterval = function(106timeoutInterval) {107'use strict';108this.timeoutInterval_ = timeoutInterval;109};110111112/**113* Sets whether to ignore the smallest and the largest values when computing114* stats.115* @param {boolean} discard Whether to discard outlier values.116*/117goog.testing.PerformanceTimer.prototype.setDiscardOutliers = function(discard) {118'use strict';119this.discardOutliers_ = discard;120};121122123/**124* @return {boolean} Whether outlier values are discarded prior to computing125* stats.126*/127goog.testing.PerformanceTimer.prototype.isDiscardOutliers = function() {128'use strict';129return this.discardOutliers_;130};131132133/**134* Executes the test function the required number of times (or until the135* test run exceeds the timeout interval, whichever comes first). Returns136* an object containing the following:137* <pre>138* {139* 'average': average execution time (ms)140* 'count': number of executions (may be fewer than expected due to timeout)141* 'maximum': longest execution time (ms)142* 'minimum': shortest execution time (ms)143* 'standardDeviation': sample standard deviation (ms)144* 'total': total execution time (ms)145* }146* </pre>147*148* @param {Function} testFn Test function whose performance is to149* be measured.150* @return {!Object} Object containing performance stats.151*/152goog.testing.PerformanceTimer.prototype.run = function(testFn) {153'use strict';154return this.runTask(new goog.testing.PerformanceTimer.Task(155/** @type {goog.testing.PerformanceTimer.TestFunction} */ (testFn)));156};157158159/**160* Executes the test function of the specified task as described in161* `run`. In addition, if specified, the set up and tear down functions of162* the task are invoked before and after each invocation of the test function.163* @see goog.testing.PerformanceTimer#run164* @param {goog.testing.PerformanceTimer.Task} task A task describing the test165* function to invoke.166* @return {!Object} Object containing performance stats.167*/168goog.testing.PerformanceTimer.prototype.runTask = function(task) {169'use strict';170var samples = [];171var testStart = goog.testing.PerformanceTimer.now_();172var totalRunTime = 0;173174var testFn = task.getTest();175var setUpFn = task.getSetUp();176var tearDownFn = task.getTearDown();177178for (var i = 0; i < this.numSamples_ && totalRunTime <= this.timeoutInterval_;179i++) {180setUpFn();181var sampleStart = goog.testing.PerformanceTimer.now_();182testFn();183var sampleEnd = goog.testing.PerformanceTimer.now_();184tearDownFn();185samples[i] = sampleEnd - sampleStart;186totalRunTime = sampleEnd - testStart;187}188189return this.finishTask_(samples);190};191192193/**194* Finishes the run of a task by creating a result object from samples, in the195* format described in `run`.196* @see goog.testing.PerformanceTimer#run197* @param {!Array<number>} samples The samples to analyze.198* @return {!Object} Object containing performance stats.199* @private200*/201goog.testing.PerformanceTimer.prototype.finishTask_ = function(samples) {202'use strict';203if (this.discardOutliers_ && samples.length > 2) {204goog.array.remove(samples, Math.min.apply(null, samples));205goog.array.remove(samples, Math.max.apply(null, samples));206}207208return goog.testing.PerformanceTimer.createResults(samples);209};210211212/**213* Executes the test function of the specified task asynchronously. The test214* function may return a Thenable to allow for asynchronous execution. In215* addition, if specified, the setUp and tearDown functions of the task are216* invoked before and after each invocation of the test function. Note,217* setUp/tearDown too may return Thenables for asynchronous execution.218* @see goog.testing.PerformanceTimer#run219* @param {goog.testing.PerformanceTimer.Task} task A task describing the test220* function to invoke.221* @return {!goog.async.Deferred} The deferred result, eventually an object222* containing performance stats.223*/224goog.testing.PerformanceTimer.prototype.runAsyncTask = function(task) {225'use strict';226var samples = [];227var testStart = goog.testing.PerformanceTimer.now_();228229var testFn = task.getTest();230var setUpFn = task.getSetUp();231var tearDownFn = task.getTearDown();232233// Note that this uses a separate code path from runTask() because234// implementing runTask() in terms of runAsyncTask() could easily cause235// a stack overflow if there are many iterations.236return goog.async.Deferred.fromPromise(this.runAsyncTaskSample_(237testFn, setUpFn, tearDownFn, samples, testStart));238};239240241/**242* Runs a task once, waits for the test function to complete asynchronously243* and starts another run if not enough samples have been collected. Otherwise244* finishes this task.245* @param {goog.testing.PerformanceTimer.TestFunction} testFn The test function.246* @param {goog.testing.PerformanceTimer.TestFunction} setUpFn The set up247* function that will be called once before the test function is run.248* @param {goog.testing.PerformanceTimer.TestFunction} tearDownFn The set up249* function that will be called once after the test function completed.250* @param {!Array<number>} samples The time samples from all runs of the test251* function so far.252* @param {number} testStart The timestamp when the first sample was started.253* @return {!Promise} A promise that returns the completed performance stats.254* @private255*/256goog.testing.PerformanceTimer.prototype.runAsyncTaskSample_ = function(257testFn, setUpFn, tearDownFn, samples, testStart) {258'use strict';259const timer = this;260let promise = Promise.resolve();261let sampleStart;262let sampleEnd;263for (let i = 0; i < timer.numSamples_; i++) {264promise = promise.then(setUpFn)265.then(() => {266'use strict';267sampleStart = goog.testing.PerformanceTimer.now_();268})269.then(testFn)270.then(() => {271'use strict';272sampleEnd = goog.testing.PerformanceTimer.now_();273})274.then(tearDownFn)275.then(() => {276'use strict';277samples.push(sampleEnd - sampleStart);278const totalRunTime = sampleEnd - testStart;279if (totalRunTime > timer.timeoutInterval_) {280// If timeout is exceeded, bypass remaining samples via281// errback.282throw Error('PerformanceTimer.Timeout');283}284});285}286return promise287.catch((err) => {288// Convert timeout error to success.289if (err instanceof Error &&290err.message === 'PerformanceTimer.Timeout') {291return true;292}293throw err;294})295.then(() => timer.finishTask_(samples));296};297298299/**300* Return the median of the samples.301* @param {!Array<number>} samples302* @return {number}303*/304goog.testing.PerformanceTimer.median = function(samples) {305'use strict';306samples.sort(function(a, b) {307'use strict';308return a - b;309});310let half = Math.floor(samples.length / 2);311if (samples.length % 2) {312return samples[half];313} else {314return (samples[half - 1] + samples[half]) / 2.0;315}316};317318319/**320* Creates a performance timer results object by analyzing a given array of321* sample timings.322* @param {!Array<number>} samples The samples to analyze.323* @return {!Object} Object containing performance stats.324*/325goog.testing.PerformanceTimer.createResults = function(samples) {326'use strict';327return {328'average': goog.math.average.apply(null, samples),329'count': samples.length,330'median': goog.testing.PerformanceTimer.median(samples),331'maximum': Math.max.apply(null, samples),332'minimum': Math.min.apply(null, samples),333'standardDeviation': goog.math.standardDeviation.apply(null, samples),334'total': goog.math.sum.apply(null, samples)335};336};337338339/**340* A test function whose performance should be measured or a setUp/tearDown341* function. It may optionally return a Thenable (e.g. a promise) to342* for asynchronous execution using the runAsyncTask method.343* @see goog.testing.PerformanceTimer#runAsyncTask344* @typedef {function():(!goog.Thenable|undefined)}345*/346goog.testing.PerformanceTimer.TestFunction;347348349350/**351* A task for the performance timer to measure. Callers can specify optional352* setUp and tearDown methods to control state before and after each run of the353* test function.354* @param {goog.testing.PerformanceTimer.TestFunction} test Test function whose355* performance is to be measured.356* @constructor357* @final358*/359goog.testing.PerformanceTimer.Task = function(test) {360'use strict';361/**362* The test function to time.363* @type {goog.testing.PerformanceTimer.TestFunction}364* @private365*/366this.test_ = test;367};368369370/**371* An optional set up function to run before each invocation of the test372* function.373* @type {goog.testing.PerformanceTimer.TestFunction}374* @private375*/376goog.testing.PerformanceTimer.Task.prototype.setUp_ = function() {};377378379/**380* An optional tear down function to run after each invocation of the test381* function.382* @type {goog.testing.PerformanceTimer.TestFunction}383* @private384*/385goog.testing.PerformanceTimer.Task.prototype.tearDown_ = function() {};386387388/**389* @return {goog.testing.PerformanceTimer.TestFunction} The test function to390* time.391*/392goog.testing.PerformanceTimer.Task.prototype.getTest = function() {393'use strict';394return this.test_;395};396397398/**399* Specifies a set up function to be invoked before each invocation of the test400* function.401* @param {goog.testing.PerformanceTimer.TestFunction} setUp The set up402* function.403* @return {!goog.testing.PerformanceTimer.Task} This task.404*/405goog.testing.PerformanceTimer.Task.prototype.withSetUp = function(setUp) {406'use strict';407this.setUp_ = setUp;408return this;409};410411412/**413* @return {goog.testing.PerformanceTimer.TestFunction} The set up function or414* the default no-op function if none was specified.415*/416goog.testing.PerformanceTimer.Task.prototype.getSetUp = function() {417'use strict';418return this.setUp_;419};420421422/**423* Specifies a tear down function to be invoked after each invocation of the424* test function.425* @param {goog.testing.PerformanceTimer.TestFunction} tearDown The tear down426* function.427* @return {!goog.testing.PerformanceTimer.Task} This task.428*/429goog.testing.PerformanceTimer.Task.prototype.withTearDown = function(tearDown) {430'use strict';431this.tearDown_ = tearDown;432return this;433};434435436/**437* @return {goog.testing.PerformanceTimer.TestFunction} The tear down function438* or the default no-op function if none was specified.439*/440goog.testing.PerformanceTimer.Task.prototype.getTearDown = function() {441'use strict';442return this.tearDown_;443};444445446