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