Bump eslint-plugin-jsdoc from 39.7.5 to 39.8.0
[benchmarks-js.git] / busy-wait.js
1 const Benchmark = require('benny')
2 const { sleep } = require('./benchmark-utils')
3
4 const timeout = 2000
5 const interval = 1000
6
7 /**
8 * @param timeoutMs
9 */
10 function dummyTimeoutBusyWait (timeoutMs) {
11 const timeoutTimestampMs = Date.now() + timeoutMs
12 // eslint-disable-next-line no-empty
13 do {} while (Date.now() < timeoutTimestampMs)
14 }
15
16 /**
17 * @param timeoutMs
18 * @param intervalMs
19 */
20 async function sleepTimeoutBusyWait (timeoutMs, intervalMs = interval) {
21 const timeoutTimestampMs = Date.now() + timeoutMs
22 do {
23 await sleep(intervalMs)
24 } while (Date.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 const tries = Math.round(timeoutMs / intervalMs)
49 let count = 0
50 const triesSetInterval = setInterval(() => {
51 count++
52 if (count === tries) {
53 clearInterval(triesSetInterval)
54 return Promise.resolve()
55 }
56 }, intervalMs)
57 }
58
59 Benchmark.suite(
60 'Busy wait',
61 Benchmark.add('dummyTimeoutBusyWait', () => {
62 dummyTimeoutBusyWait(timeout)
63 }),
64 Benchmark.add('sleepTimeoutBusyWait', async () => {
65 await sleepTimeoutBusyWait(timeout)
66 }),
67 Benchmark.add('divideAndConquerTimeoutBusyWait', async () => {
68 await divideAndConquerTimeoutBusyWait(timeout)
69 }),
70 Benchmark.add('setIntervalTimeoutBusyWait', async () => {
71 await setIntervalTimeoutBusyWait(timeout)
72 }),
73 Benchmark.cycle(),
74 Benchmark.complete(),
75 Benchmark.save({ file: 'busy-wait', format: 'json', details: true }),
76 Benchmark.save({ file: 'busy-wait', format: 'chart.html', details: true }),
77 Benchmark.save({ file: 'busy-wait', format: 'table.html', details: true })
78 )