X-Git-Url: https://git.piment-noir.org/?a=blobdiff_plain;f=busy-wait.js;h=f2d10f3cd24f3d99d3a30d0c6fca6463991faf5f;hb=7fd91296ddf293e0ef084408618f4cc1f551de92;hp=4742018a698db86fb50aadb5656d42fde29d8f56;hpb=ed2968f2ee816cb47841f537bcbfb8590aa7bbb9;p=benchmarks-js.git diff --git a/busy-wait.js b/busy-wait.js index 4742018..f2d10f3 100644 --- a/busy-wait.js +++ b/busy-wait.js @@ -1,30 +1,71 @@ const Benchmark = require('benchmark') -const { LIST_FORMATTER } = require('./benchmark-utils') +const { LIST_FORMATTER, sleep } = require('./benchmark-utils') const suite = new Benchmark.Suite() const timeout = 2000 +const interval = 1000 +/** + * @param timeoutMs + */ function dummyTimeoutBusyWait (timeoutMs) { - const timeoutDateMs = Date.now() + timeoutMs - do {} while (Date.now() < timeoutDateMs) + const timeoutTimestampMs = Date.now() + timeoutMs + // eslint-disable-next-line no-empty + do {} while (Date.now() < timeoutTimestampMs) } -function setIntervalTimeoutBusyWait (timeoutMs, delayMs = 200) { - const tries = Math.round(timeoutMs / delayMs) +/** + * @param timeoutMs + */ +async function sleepTimeoutBusyWait (timeoutMs) { + const timeoutTimestampMs = Date.now() + timeoutMs + do { + await sleep(interval) + } while (Date.now() < timeoutTimestampMs) +} + +/** + * @param timeoutMs + * @param intervalMs + */ +async function divideAndConquerTimeoutBusyWait ( + timeoutMs, + intervalMs = interval +) { + const tries = Math.round(timeoutMs / intervalMs) + let count = 0 + do { + count++ + await sleep(intervalMs) + } while (count <= tries) +} + +/** + * @param timeoutMs + * @param intervalMs + */ +function setIntervalTimeoutBusyWait (timeoutMs, intervalMs = interval) { + const tries = Math.round(timeoutMs / intervalMs) let count = 0 const triesSetInterval = setInterval(() => { count++ if (count === tries) { clearInterval(triesSetInterval) } - }, delayMs) + }, intervalMs) } suite .add('dummyTimeoutBusyWait', function () { dummyTimeoutBusyWait(timeout) }) + .add('sleepTimeoutBusyWait', async function () { + sleepTimeoutBusyWait(timeout) + }) + .add('divideAndConquerTimeoutBusyWait', async function () { + await divideAndConquerTimeoutBusyWait(timeout) + }) .add('setIntervalTimeoutBusyWait', function () { setIntervalTimeoutBusyWait(timeout) }) @@ -35,7 +76,7 @@ suite console.log( 'Fastest is ' + LIST_FORMATTER.format(this.filter('fastest').map('name')) ) - // eslint-disable-next-line no-process-exit + // eslint-disable-next-line n/no-process-exit process.exit() }) .run()