Created
January 22, 2021 12:04
-
-
Save StackTrac3/d6e56bb9792f5545243a7c63a8e3ac78 to your computer and use it in GitHub Desktop.
Super simple JavaScript execution timing
This file contains hidden or 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
const microtime = (() => { | |
const currentNano = () => { | |
const [a, b] = process.hrtime() | |
return a * 1000000000 + b | |
} | |
const nanoToMilli = (ns) => (ns / 1000000).toFixed(3) | |
const markers = { | |
'-1': currentNano() | |
} | |
return { | |
mark(id = -1) { | |
markers[id] = currentNano() | |
}, | |
since(id = -1) { | |
return nanoToMilli(currentNano() - markers[id]) | |
} | |
} | |
})() | |
// Demo code | |
const log = (mt, message) => console.log(`[${mt}]`, message) | |
const { mark, since } = microtime | |
// Mark and since without an argument may be | |
// used to track and overwrite a single moment | |
mark() | |
log(since(), 'a') | |
// This will demonstrate named marks | |
mark('character-b') | |
setTimeout(() => log(since('character-b'), 'b'), 50) | |
setTimeout(() => log(since('character-c'), 'c'), 60) | |
mark('character-c') | |
/* Demo Output | |
> [~0.050 ms] a | |
> [~50.000 ms] b | |
> [~60.000 ms] c | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment