Created
February 3, 2012 22:14
Revisions
-
mcavage created this gist
Feb 3, 2012 .There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,77 @@ /** * Figure out how long it takes for a method to execute. * * @param {func} method to test * @param {int} iterations number of executions. * @param {Array} args to pass in. * @param {T} context the context to call the method in. * @return {int} the time it took, in milliseconds to execute. */ var bench = function (method, iterations, args, context) { var time = 0; var timer = function (action) { var d = +(new Date); if (time < 1 || action === 'start') { time = d; return 0; } else if (action === 'stop') { var t = d - time; time = 0; return t; } else { return d - time; } }; var result = []; var i = 0; timer('start'); while (i < iterations) { result.push(method.apply(context, args)); i++; } var execTime = timer('stop'); if ( typeof console === "object") { console.log("Mean execution time was: ", execTime / iterations); console.log("Sum execution time was: ", execTime); console.log("Result of the method call was:", result[0]); } return execTime; }; function noop() { return 2 * 2; } function getFileAndLine() { var self = this; var saveLimit = Error.stackTraceLimit; var savePrepare = Error.prepareStackTrace; Error.stackTraceLimit = 1; Error.captureStackTrace(this, getFileAndLine); Error.prepareStackTrace = function(_, stack) { self.file = stack[0].getFileName(); self.line = stack[0].getLineNumber(); }; this.stack; Error.stackTraceLimit = saveLimit; Error.prepareStackTrace = savePrepare; return { file: self.file, line: self.line } } bench(noop, 10000, [], this); console.log('\n\n\n'); bench(getFileAndLine, 10000, [], this);