Skip to content

Instantly share code, notes, and snippets.

@loopmode
Created July 5, 2017 15:55
Show Gist options
  • Save loopmode/5d61acaf41d16a4e5aa91a6bc07f92d1 to your computer and use it in GitHub Desktop.
Save loopmode/5d61acaf41d16a4e5aa91a6bc07f92d1 to your computer and use it in GitHub Desktop.
A benchmark utility that measures the execution times of functions in an object
/*
Usage:
this.benchmarks = new Benchmarks({
target: this,
functions: ['performLookups', 'createIsotope', 'updateIsotope', 'fitVideos', 'applyRandomSize']
});
*/
/**
* A benchmark utility that measures the execution times of functions in an object, if enabled.
* Disabled by default.
* Enabled/disabled state is persisted in browser storage, e.g. survives page refresh.
*
* @param {Object} options - A configuration object
* @param {Object} options.target - The target object that contains the functions
* @param {Array} options.functions - Names of the functions in the target that should be benchmarked
* @param {Object} [storage=window.localStorage] - A persistence object that supports the web storage API
* @param {Object} [logger=window.console] - An object with a `log` function. Defaults to window.console
*/
function Benchmarks(options) {
options = options || {};
var target = options.target;
var functions = options.functions;
var storage = options.storage || window.localStorage;
var logger = options.logger || window.console;
var backups = {};
var lsKey = 'Benchmarks.enabled';
if (storage.getItem != undefined && !!storage.getItem(lsKey)) {
setup();
}
this.enable = function () {
setup();
storage.setItem(lsKey, true);
};
this.disable = function () {
teardown();
storage.removeItem(lsKey);
};
function setup() {
functions.forEach(function (name) {
var fn = backups[name] || target[name];
backups[name] = fn;
target[name] = function () {
var started = performance.now();
fn.apply(target, arguments);
logger.log(fn.name + ' done in ' + (performance.now() - started) + 'ms');
};
Object.defineProperty(target[name], 'name', { value: 'Benchmarked' + fn.name });
});
}
function teardown() {
functions.forEach(function (name) {
target[name] = backups[name];
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment