Simple JavaScript profiling timer script.

I had a need to write a small script that I could easily use to time bits of JavaScript code in order to profile it. Chrome's dev tools has lots of useful profiling tools but sometimes you just want some helpful code snippets.
var timers = [];
function startTimer(name) {
for (var index in timers) {
var timer = timers[index];
if (timer.name === name)
timers.splice(index, 1);
}
var timer = {
startTime: new Date(),
name: name
};
timers.push(timer);
}
function stopTimer(name) {
for (var index in timers) {
var timer = timers[index];
if (timer.name === name) {
var elapsed = (new Date()) - timer.startTime;
timers.splice(index, 1);
console.log(timer.name + ": " + elapsed + "ms");
}
}
}
Just add this script to your page and then call startTimer('some name');
to begin timing. To stop simply do stopTimer('some name')
(name is case-sensitive). This script has the advantage of letting you start multiple simultaneous timers. When stopTimer
is called it will print a line to the JavaScript console with the results.
Just be careful because as of this writing front-end JavaScript is still single-threaded. In other words, starting 100 simultaneous timers is a bad idea. Also keep in mind that running timers in your code will slow the code down making your timers the very cause of some of the slowness you measure. Five running timers or less seems to have little impact in most situations I've tried.
Thanks to Carlos Garcia-Dubus's idea, the script has been updated to no longer use intervals. It now just checks the time when it starts and again when it stops and calculates the difference. Not sure why I didn't think of that in the first place; kudos to Carlos :)
I don't know what the upper limit on the number of timers would be now before they would cause performance issues in your code but the number is probably so high that I doubt it matters.
var timers = [];
function startTimer(name) {
for (var index in timers) {
var timer = timers[index];
if (timer.name === name)
timers.splice(index, 1);
}
var timer = {
startTime: new Date(),
name: name
};
timers.push(timer);
}
function stopTimer(name) {
for (var index in timers) {
var timer = timers[index];
if (timer.name === name) {
var elapsed = (new Date()) - timer.startTime;
timers.splice(index, 1);
document.getElementById('result').innerHTML += timer.name + ": " + elapsed + "ms<br />";
//console.log(timer.name + ": " + elapsed + "ms");
}
}
}