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) {
11 const timeoutTimestampMs = Date.now() + timeoutMs
7fd91296 12 // eslint-disable-next-line no-empty
a6c34381
JB
13 do {} while (Date.now() < timeoutTimestampMs)
14}
15
e9bfc28e
JB
16/**
17 * @param timeoutMs
18 */
a8bf8b7d 19async function sleepTimeoutBusyWait (timeoutMs) {
a9c78d5d 20 const timeoutTimestampMs = Date.now() + timeoutMs
a8bf8b7d
JB
21 do {
22 await sleep(interval)
23 } while (Date.now() < timeoutTimestampMs)
a9c78d5d
JB
24}
25
26/**
27 * @param timeoutMs
e47f67db 28 * @param intervalMs
a9c78d5d 29 */
a8bf8b7d
JB
30async function divideAndConquerTimeoutBusyWait (
31 timeoutMs,
32 intervalMs = interval
33) {
e47f67db 34 const tries = Math.round(timeoutMs / intervalMs)
a9c78d5d
JB
35 let count = 0
36 do {
37 count++
e47f67db 38 await sleep(intervalMs)
a9c78d5d 39 } while (count <= tries)
ed2968f2
JB
40}
41
e9bfc28e
JB
42/**
43 * @param timeoutMs
e47f67db 44 * @param intervalMs
e9bfc28e 45 */
a8bf8b7d 46function setIntervalTimeoutBusyWait (timeoutMs, intervalMs = interval) {
e47f67db 47 const tries = Math.round(timeoutMs / intervalMs)
ed2968f2
JB
48 let count = 0
49 const triesSetInterval = setInterval(() => {
50 count++
51 if (count === tries) {
52 clearInterval(triesSetInterval)
53 }
e47f67db 54 }, intervalMs)
ed2968f2
JB
55}
56
662a730a
JB
57Benchmark.suite(
58 'Busy wait',
59 Benchmark.add('dummyTimeoutBusyWait', () => {
a6c34381 60 dummyTimeoutBusyWait(timeout)
662a730a
JB
61 }),
62 Benchmark.add('sleepTimeoutBusyWait', async () => {
ed40d2b0 63 await sleepTimeoutBusyWait(timeout)
662a730a
JB
64 }),
65 Benchmark.add('divideAndConquerTimeoutBusyWait', async () => {
a9c78d5d 66 await divideAndConquerTimeoutBusyWait(timeout)
662a730a
JB
67 }),
68 Benchmark.add('setIntervalTimeoutBusyWait', () => {
ed2968f2 69 setIntervalTimeoutBusyWait(timeout)
662a730a
JB
70 }),
71 Benchmark.cycle(),
72 Benchmark.complete(),
73 Benchmark.save({ file: 'busy-wait', format: 'json', details: true }),
74 Benchmark.save({ file: 'busy-wait', format: 'chart.html', details: true }),
75 Benchmark.save({ file: 'busy-wait', format: 'table.html', details: true })
76)