Created
August 24, 2018 10:26
-
-
Save myobie/36ac252b99c43be42a244773d880d323 to your computer and use it in GitHub Desktop.
A nicer API for performance time measurements in the browser
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
export function create (name) { | |
const nameStart = `${name} start` | |
window.performance.mark(nameStart) | |
return { | |
log: () => { log(name) }, | |
end: () => { end(name) } | |
} | |
} | |
export function log (name) { | |
const duration = end(name) | |
console.debug(`${name} in ${duration}ms`) | |
} | |
export function end (name) { | |
const nameStart = `${name} start` | |
const nameEnd = `${name} end` | |
window.performance.mark(nameEnd) | |
window.performance.measure(name, nameStart, nameEnd) | |
const measures = window.performance.getEntriesByName(name) | |
if (measures.length > 0) { | |
const measure = measures[0] | |
return measure.duration | |
} else { | |
return 0 | |
} | |
} |
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
import * as timing from './timing' | |
// Create a timing, then log it later | |
const _timing = timing.create('a long delay') | |
setTimeout(() => { _timing.log() }, 8090) | |
// Create a timing, then manually end it | |
const _timingName = 'recursive work' | |
function doTheThing(nestingAmount = 0) { | |
if (nestingAmount === 0) { | |
timing.create(_timingName) | |
} | |
if (nestingAmount === 1000) { | |
timing.log(_timingName) | |
} | |
doTheThing(nestingAmount + 1) | |
} | |
doTheThing() // will recurse 1000 times and then log how long that took |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment