build(deps-dev): apply updates
[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) {
1652efb2
JB
48 return new Promise(resolve => {
49 const tries = Math.round(timeoutMs / intervalMs)
50 let count = 0
51 const triesSetInterval = setInterval(() => {
52 count++
53 if (count === tries) {
54 clearInterval(triesSetInterval)
55 return resolve()
56 }
57 }, intervalMs)
58 })
ed2968f2
JB
59}
60
662a730a
JB
61Benchmark.suite(
62 'Busy wait',
63 Benchmark.add('dummyTimeoutBusyWait', () => {
a6c34381 64 dummyTimeoutBusyWait(timeout)
662a730a
JB
65 }),
66 Benchmark.add('sleepTimeoutBusyWait', async () => {
ed40d2b0 67 await sleepTimeoutBusyWait(timeout)
662a730a
JB
68 }),
69 Benchmark.add('divideAndConquerTimeoutBusyWait', async () => {
a9c78d5d 70 await divideAndConquerTimeoutBusyWait(timeout)
662a730a 71 }),
eab47c66
JB
72 Benchmark.add('setIntervalTimeoutBusyWait', async () => {
73 await setIntervalTimeoutBusyWait(timeout)
662a730a
JB
74 }),
75 Benchmark.cycle(),
76 Benchmark.complete(),
77 Benchmark.save({ file: 'busy-wait', format: 'json', details: true }),
78 Benchmark.save({ file: 'busy-wait', format: 'chart.html', details: true }),
79 Benchmark.save({ file: 'busy-wait', format: 'table.html', details: true })
4b16770a
JB
80).catch(err => {
81 console.error(err)
82})