Reputation: 3408
I'm trying to make a function that will time other JavaScript functions.
Basically, it would do something like this:
var start = new Date().getTime();
// the function
var end = new Date().getTime();
return end - start;
But, I'd like to be able to call it on any function. For example, I could say timeThisFunction(add)
or timeThisFunction(subtract)
and it would see how long it took the functions add
and subtract
to run.
Is this possible in JavaScript? I know there's scoping issues that could be involved. What's the best way to implement it?
Upvotes: 3
Views: 2194
Reputation: 399
Just as an option, you could make timimng function to perform some work for you (context binding, arguments passing).
As a downside, apply
is known to be slower then usual function call, so this will no be 100% accurate, but if what is needed is to compare two different implementations of the same function, then it can be useful.
function timeIt(fn, context) {
var args = Array.prototype.slice.call(arguments, 2),
start = new Date().getTime();
fn.apply(context, args);
return new Date().getTime() - start;
}
Example usage would be:
function log(what, smthElse) { //ugly function for demonstration
console.log(what + ' ' + smthElse);
};
timeIt(log, null, 'hello', 'stranger');
Upvotes: 1
Reputation: 413712
If you just want to be able to time a single call to a function, it's pretty easy:
function timer(fn) {
var start = new Date().getTime();
fn();
var end = new Date().getTime();
return end - start;
}
Passing functions around is no different than passing around any other sort of value.
If you need to time a function that requires parameters, just wrap it in another function:
var millis = timer(function() { theRealFunction(something, 22); });
The extra wrapper function will add a tiny amount of overhead, but it shouldn't matter for most purposes.
Similarly, if you need to time a function that expects this
to be bound, you'd bind it before the call:
var millis = timer(someObject.someMethod.bind(someObject));
Now, all that said, if you've got a single JavaScript function call that takes enough time for this mechanism to give meaningful results, then there's probably some serious performance flaw worth investigating.
Upvotes: 4