Switch all benchmarks to benny
[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 */
19 async function sleepTimeoutBusyWait (timeoutMs) {
20 const timeoutTimestampMs = Date.now() + timeoutMs
21 do {
22 await sleep(interval)
23 } while (Date.now() < timeoutTimestampMs)
24 }
25
26 /**
27 * @param timeoutMs
28 * @param intervalMs
29 */
30 async function divideAndConquerTimeoutBusyWait (
31 timeoutMs,
32 intervalMs = interval
33 ) {
34 const tries = Math.round(timeoutMs / intervalMs)
35 let count = 0
36 do {
37 count++
38 await sleep(intervalMs)
39 } while (count <= tries)
40 }
41
42 /**
43 * @param timeoutMs
44 * @param intervalMs
45 */
46 function setIntervalTimeoutBusyWait (timeoutMs, intervalMs = interval) {
47 const tries = Math.round(timeoutMs / intervalMs)
48 let count = 0
49 const triesSetInterval = setInterval(() => {
50 count++
51 if (count === tries) {
52 clearInterval(triesSetInterval)
53 }
54 }, intervalMs)
55 }
56
57 Benchmark.suite(
58 'Busy wait',
59 Benchmark.add('dummyTimeoutBusyWait', () => {
60 dummyTimeoutBusyWait(timeout)
61 }),
62 Benchmark.add('sleepTimeoutBusyWait', async () => {
63 await sleepTimeoutBusyWait(timeout)
64 }),
65 Benchmark.add('divideAndConquerTimeoutBusyWait', async () => {
66 await divideAndConquerTimeoutBusyWait(timeout)
67 }),
68 Benchmark.add('setIntervalTimeoutBusyWait', () => {
69 setIntervalTimeoutBusyWait(timeout)
70 }),
71 Benchmark.cycle(),
72 Benchmark.complete(),
73 Benchmark.save({ file: 'busy-wait', format: 'json', details: true }),
74 Benchmark.save({ file: 'busy-wait', format: 'chart.html', details: true }),
75 Benchmark.save({ file: 'busy-wait', format: 'table.html', details: true })
76 )