build: bump volta node version
[benchmarks-js.git] / busy-wait.mjs
1 import { bench, group, run } from 'tatami-ng'
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 group('Busy wait', () => {
63 bench('dummyTimeoutBusyWait', () => {
64 dummyTimeoutBusyWait(timeout)
65 })
66 bench('sleepTimeoutBusyWait', async () => {
67 await sleepTimeoutBusyWait(timeout)
68 })
69 bench('divideAndConquerTimeoutBusyWait', async () => {
70 await divideAndConquerTimeoutBusyWait(timeout)
71 })
72 bench('setIntervalTimeoutBusyWait', async () => {
73 await setIntervalTimeoutBusyWait(timeout)
74 })
75 })
76
77 await run({
78 units: true
79 })