Last active
February 12, 2016 06:43
-
-
Save tebba-von-mathenstein/ef1cc90fdfad92d8db12 to your computer and use it in GitHub Desktop.
A lightweight benchmarking utility to compare multiple versions of a function
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
/** | |
* reports the speed of a function. | |
* Params: | |
* f: the function | |
* fParams: array, the parameters f will be called with. | |
* minTime: number, the minimum amount of time to run each function in seconds. | |
* verbose: boolean, print to the console if true. | |
* | |
* Returns: | |
* iterations per second benchmark value | |
*/ | |
function benchmarkFunction(f, fParams, minTime, verbose) { | |
// Benchmarking time values | |
var min = 0; | |
var max = 0; | |
var totalTime = 0 | |
var iterations = 0; | |
while(totalTime < minTime * 1000){ | |
// Time the function -- none of the other overhead | |
var startTime = new Date().getTime(); | |
f.apply(null, fParams); | |
var endTime = new Date().getTime(); | |
// collect benchmarks | |
var iterationTime = endTime - startTime; | |
totalTime += iterationTime; | |
iterations++; | |
} | |
iterationsPerSecond = (iterations / (totalTime / 1000)).toFixed(0); | |
if(verbose) { | |
console.log("\n========= " + f.name + " ============="); | |
console.log(" Params: " + fParams); | |
console.log(" Iterations: " + iterations); | |
console.log(" Total Time: " + totalTime); | |
console.log(" Slowest iteration: " + max + "ms"); | |
console.log(" Fastest iteration: " + min + "ms"); | |
console.log(" Iterations per: " + iterationsPerSecond + "ms\n"); | |
} | |
return iterationsPerSecond; | |
} | |
/** | |
* reports the speed of a function. | |
* Params: | |
* functionArray: array, the function | |
* fParams: array, the parameters f will be called with. | |
* minTime: number, the minimum amount of time to run each function in seconds. | |
* verbose: boolean, print to the console if true. | |
* | |
* Returns: | |
* iterations per second benchmark value | |
*/ | |
function compareFunctions(functionArray, fParams, minTime, verbose) { | |
var results = []; | |
for(var i = 0; i < functionArray.length; i++) { | |
var fIPS = benchmarkFunction(functionArray[i], fParams, minTime, verbose) | |
results.push({f: functionArray[i].name, iterationsPerSecond: fIPS}); | |
} | |
// Most iterations per second first (fastest) | |
results.sort(function(a, b) { | |
return b.iterationsPerSecond - a.iterationsPerSecond; | |
}); | |
for(i in results) { | |
console.log(results[i]); | |
} | |
} | |
module.exports = { | |
benchmarkFunction: benchmarkFunction, | |
compareFunctions: compareFunctions | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment