Last active
November 2, 2015 22:48
-
-
Save garris/9b6dc4d8ab1bf363c7f5 to your computer and use it in GitHub Desktop.
A JS stopwatch object that is useful for spot-performance testing JS operations.
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
function stopwatch(label, resolution) { | |
if (resolution === undefined) { | |
resolution = 1; | |
} | |
if (!label) { | |
label = ''; | |
} | |
this.label = label; | |
this.isRunning = false; | |
this.lastLapTime = 0.0; | |
this.startTime = 0.0; | |
this.stopTime = 0.0; | |
this.selfTime = 0.0; | |
this.laps = []; | |
function getRoundedDelta(a, b) { | |
return Math.round((a - b)*resolution)/resolution; | |
} | |
this.getTime = () => { | |
return Math.round(window.performance.now() * resolution) / resolution; | |
}; | |
this.lap = (lapLabel, toConsole) => { | |
var lapTime = this.getTime(); | |
if (!this.lastLapTime) { | |
this.lastLapTime = this.startTime; | |
} | |
var lapSelfTime = getRoundedDelta(lapTime, this.lastLapTime); | |
if (!lapLabel) { | |
lapLabel = ''; | |
} | |
this.laps.push({ | |
id: this.laps.length, | |
label: lapLabel, | |
time: lapTime, | |
self: lapSelfTime | |
}); | |
this.lastLapTime = lapTime; | |
if (toConsole) { | |
console.log(lapLabel + ' ' + lapSelfTime + "ms") | |
} | |
return lapSelfTime; | |
}; | |
this.stop = (toConsole) => { | |
this.stopTime = this.getTime(); | |
this.selfTime = getRoundedDelta(this.stopTime, this.startTime); | |
if (toConsole) { | |
console.log(label + ' ' + this.selfTime + "ms") | |
} | |
this.isRunning = false; | |
return this.selfTime; | |
}; | |
this.start = () => { | |
this.isRunning = true; | |
this.startTime = this.getTime(); | |
}; | |
this.start(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment