build: bump volta pnpm version
[benchmarks-js.git] / busy-wait.mjs
1 import Benchmark from 'benny'
2 import { sleep } from './benchmark-utils.mjs'
3
4 const timeout = 2000
5 const interval = 1000
6
7 /**
8 * @param timeoutMs
9 */
10 function dummyTimeoutBusyWait (timeoutMs) {
11 const timeoutTimestampMs = performance.now() + timeoutMs
12 // eslint-disable-next-line no-empty
13 do {} while (performance.now() < timeoutTimestampMs)
14 }
15
16 /**
17 * @param timeoutMs
18 * @param intervalMs
19 */
20 async function sleepTimeoutBusyWait (timeoutMs, intervalMs = interval) {
21 const timeoutTimestampMs = performance.now() + timeoutMs
22 do {
23 await sleep(intervalMs)
24 } while (performance.now() < timeoutTimestampMs)
25 }
26
27 /**
28 * @param timeoutMs
29 * @param intervalMs
30 */
31 async function divideAndConquerTimeoutBusyWait (
32 timeoutMs,
33 intervalMs = interval
34 ) {
35 const tries = Math.round(timeoutMs / intervalMs)
36 let count = 0
37 do {
38 count++
39 await sleep(intervalMs)
40 } while (count <= tries)
41 }
42
43 /**
44 * @param timeoutMs
45 * @param intervalMs
46 */
47 async function setIntervalTimeoutBusyWait (timeoutMs, intervalMs = interval) {
48 await 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 resolve()
56 }
57 }, intervalMs)
58 })
59 }
60
61 Benchmark.suite(
62 'Busy wait',
63 Benchmark.add('dummyTimeoutBusyWait', () => {
64 dummyTimeoutBusyWait(timeout)
65 }),
66 Benchmark.add('sleepTimeoutBusyWait', async () => {
67 await sleepTimeoutBusyWait(timeout)
68 }),
69 Benchmark.add('divideAndConquerTimeoutBusyWait', async () => {
70 await divideAndConquerTimeoutBusyWait(timeout)
71 }),
72 Benchmark.add('setIntervalTimeoutBusyWait', async () => {
73 await setIntervalTimeoutBusyWait(timeout)
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 })
80 ).catch(console.error)