Created
October 8, 2012 06:51
-
-
Save theorm/3851086 to your computer and use it in GitHub Desktop.
StopWatch time measurement class for profiling javascript apps.
This file contains 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
/* | |
StopWatch. A time profiler. | |
Use: | |
var stopwatch = StopWatch("My Stop Watch"); | |
// ... do something here | |
stopwatch.lap("step1"); | |
// ... do something more | |
stopwatch.lap("step2").print(); | |
// Console log at this point: | |
// [SW "My Stop Watch"]: step1 = 12 ms, step2 = 20 ms | |
*/ | |
function StopWatch(name) { | |
this._name = name; | |
this._laps = new Array(); | |
this._start = new Date().getTime(); | |
} | |
StopWatch.prototype.lap = function(name) { | |
var time = new Date().getTime(); | |
if (!name) name = '' + this._laps.length; | |
this._laps.push({'name' : name, 'timestamp' : time}); | |
return this; | |
} | |
StopWatch.prototype.print = function() { | |
if (!console) return; | |
var lastTimestamp = this._start; | |
var text = '[SW "' + this._name + '"]:'; | |
for (var i =0; i < this._laps.length; i++) { | |
var lap = this._laps[i]; | |
text += ' ' + lap['name'] + ' = ' + (lap['timestamp']-lastTimestamp) + ' ms'; | |
if (i+1 < this._laps.length) text += ',\t'; | |
lastTimestamp = lap['timestamp']; | |
} | |
console.log(text); | |
return this; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment