Skip to content

Instantly share code, notes, and snippets.

@sethmcleod
Last active December 8, 2016 22:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sethmcleod/8e50cbae440e7012b2b2 to your computer and use it in GitHub Desktop.
Save sethmcleod/8e50cbae440e7012b2b2 to your computer and use it in GitHub Desktop.
Javascript constructor for testing function execution speeds
function speedTest(testImplement, testParams, repetitions = 10000) {
// code to be tested
this.testImplement = testImplement;
// parameters needed for code
this.testParams = testParams;
// optional number of reps; higher = better average
this.repetitions = repetitions;
this.average = 0;
}
// add methods to Prototype for better preformance
speedTest.prototype = {
startTest: () => {
let beginTime, endTime, sumTimes = 0;
for (let i = 0, x = this.repetitions; i < x; i++) {
beginTime = +new Date();
this.testImplement( this.testParams );
endTime = +new Date();
sumTimes += endTime - beginTime;
}
this.average = sumTimes / this.repetitions;
return console.log('Average executions across ' + this.repetitions + ': ' + this.average);
},
};
@sethmcleod
Copy link
Author

To use, create a new test:

function exampleFunction (param1, param2) {
  console.log(param1 + " " + param2 );
}
var exampleTest = new SpeedTest(exampleFunction, ["foo", "bar"], 20000)

Then call the startTest method:

exampleTest.startTest()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment