Created
May 16, 2019 16:59
-
-
Save andykais/ae526eb8bd18925f12a0bbc2609402c9 to your computer and use it in GitHub Desktop.
A couple of handy timing functions I use often
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
// async | |
const timeout = n => new Promise(resolve => setTimeout(resolve, n)) | |
// sync | |
const sleep = n => Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, n) | |
// async | |
const scheduleAsync = startAtEpoch => async fn => { | |
const now = Date.now() | |
const millisecondsTillStartAt = startAtEpoch - now | |
await timeout(millisecondsTillStartAt) | |
return fn() | |
} | |
// sync | |
const scheduleSync = startAtEpoch => fn => { | |
let now | |
do { | |
now = Date.now() | |
} while (now < startAtEpoch) | |
fn() | |
} | |
// async | |
const measureAsync = prefix => async fn => { | |
const start = process.hrtime() | |
console.log(prefix, 'starting at', Date.now()) | |
await fn() | |
const end = process.hrtime(start) | |
console.log(prefix, 'took', end[0] + end[1] / 1e9) | |
} | |
// sync | |
const measureSync = prefix => fn => { | |
const start = process.hrtime() | |
console.log(prefix, 'starting at', Date.now()) | |
fn() | |
const end = process.hrtime(start) | |
console.log(prefix, 'took', end[0] + end[1] / 1e9) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment