Apply dependencies update
[benchmarks-js.git] / busy-wait.js
CommitLineData
662a730a
JB
1const Benchmark = require('benny')
2const { sleep } = require('./benchmark-utils')
ed2968f2
JB
3
4const timeout = 2000
a8bf8b7d 5const interval = 1000
ed2968f2 6
a6c34381
JB
7/**
8 * @param timeoutMs
9 */
10function dummyTimeoutBusyWait (timeoutMs) {
41672b12 11 const timeoutTimestampMs = performance.now() + timeoutMs
7fd91296 12 // eslint-disable-next-line no-empty
41672b12 13 do {} while (performance.now() < timeoutTimestampMs)
a6c34381
JB
14}
15
e9bfc28e
JB
16/**
17 * @param timeoutMs
eab47c66 18 * @param intervalMs
e9bfc28e 19 */
eab47c66 20async function sleepTimeoutBusyWait (timeoutMs, intervalMs = interval) {
41672b12 21 const timeoutTimestampMs = performance.now() + timeoutMs
a8bf8b7d 22 do {
eab47c66 23 await sleep(intervalMs)
41672b12 24 } while (performance.now() < timeoutTimestampMs)
a9c78d5d
JB
25}
26
27/**
28 * @param timeoutMs
e47f67db 29 * @param intervalMs
a9c78d5d 30 */
a8bf8b7d
JB
31async function divideAndConquerTimeoutBusyWait (
32 timeoutMs,
33 intervalMs = interval
34) {
e47f67db 35 const tries = Math.round(timeoutMs / intervalMs)
a9c78d5d
JB
36 let count = 0
37 do {
38 count++
e47f67db 39 await sleep(intervalMs)
a9c78d5d 40 } while (count <= tries)
ed2968f2
JB
41}
42
e9bfc28e
JB
43/**
44 * @param timeoutMs
e47f67db 45 * @param intervalMs
e9bfc28e 46 */
eab47c66 47async function setIntervalTimeoutBusyWait (timeoutMs, intervalMs = interval) {
e47f67db 48 const tries = Math.round(timeoutMs / intervalMs)
ed2968f2
JB
49 let count = 0
50 const triesSetInterval = setInterval(() => {
51 count++
52 if (count === tries) {
53 clearInterval(triesSetInterval)
eab47c66 54 return Promise.resolve()
ed2968f2 55 }
e47f67db 56 }, intervalMs)
ed2968f2
JB
57}
58
662a730a
JB
59Benchmark.suite(
60 'Busy wait',
61 Benchmark.add('dummyTimeoutBusyWait', () => {
a6c34381 62 dummyTimeoutBusyWait(timeout)
662a730a
JB
63 }),
64 Benchmark.add('sleepTimeoutBusyWait', async () => {
ed40d2b0 65 await sleepTimeoutBusyWait(timeout)
662a730a
JB
66 }),
67 Benchmark.add('divideAndConquerTimeoutBusyWait', async () => {
a9c78d5d 68 await divideAndConquerTimeoutBusyWait(timeout)
662a730a 69 }),
eab47c66
JB
70 Benchmark.add('setIntervalTimeoutBusyWait', async () => {
71 await setIntervalTimeoutBusyWait(timeout)
662a730a
JB
72 }),
73 Benchmark.cycle(),
74 Benchmark.complete(),
75 Benchmark.save({ file: 'busy-wait', format: 'json', details: true }),
76 Benchmark.save({ file: 'busy-wait', format: 'chart.html', details: true }),
77 Benchmark.save({ file: 'busy-wait', format: 'table.html', details: true })
78)