Created
February 3, 2012 22:14
-
-
Save mcavage/1733234 to your computer and use it in GitHub Desktop.
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 characters
/** | |
* 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); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
$ node fileline.js
Mean execution time was: 0.0001
Sum execution time was: 1
Result of the method call was: 4
Mean execution time was: 0.011
Sum execution time was: 110
Result of the method call was: { file: '/Users/mark/work/fileline.js', line: 31 }
bluesnoop:work mark$