build(deps-dev): apply updates
[benchmarks-js.git] / busy-wait.mjs
... / ...
CommitLineData
1import { bench, group, run } from 'tatami-ng'
2
3import { sleep } from './benchmark-utils.mjs'
4
5const timeout = 2000
6const interval = 1000
7
8/**
9 * @param timeoutMs
10 */
11function 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 */
21async 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 */
32async 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 */
48async 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
62group('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
77await run({
78 units: true
79})