Busy wait with a sleep inside.
[benchmarks-js.git] / busy-wait.js
1 const Benchmark = require('benchmark')
2 const { LIST_FORMATTER, sleep } = require('./benchmark-utils')
3
4 const suite = new Benchmark.Suite()
5
6 const timeout = 2000
7 const interval = 1000
8
9 /**
10 * @param timeoutMs
11 */
12 async function sleepTimeoutBusyWait (timeoutMs) {
13 const timeoutTimestampMs = Date.now() + timeoutMs
14 do {
15 await sleep(interval)
16 } while (Date.now() < timeoutTimestampMs)
17 }
18
19 /**
20 * @param timeoutMs
21 * @param intervalMs
22 */
23 async function divideAndConquerTimeoutBusyWait (
24 timeoutMs,
25 intervalMs = interval
26 ) {
27 const tries = Math.round(timeoutMs / intervalMs)
28 let count = 0
29 do {
30 count++
31 await sleep(intervalMs)
32 } while (count <= tries)
33 }
34
35 /**
36 * @param timeoutMs
37 * @param intervalMs
38 */
39 function setIntervalTimeoutBusyWait (timeoutMs, intervalMs = interval) {
40 const tries = Math.round(timeoutMs / intervalMs)
41 let count = 0
42 const triesSetInterval = setInterval(() => {
43 count++
44 if (count === tries) {
45 clearInterval(triesSetInterval)
46 }
47 }, intervalMs)
48 }
49
50 suite
51 .add('sleepTimeoutBusyWait', async function () {
52 sleepTimeoutBusyWait(timeout)
53 })
54 .add('divideAndConquerTimeoutBusyWait', async function () {
55 await divideAndConquerTimeoutBusyWait(timeout)
56 })
57 .add('setIntervalTimeoutBusyWait', function () {
58 setIntervalTimeoutBusyWait(timeout)
59 })
60 .on('cycle', function (event) {
61 console.log(event.target.toString())
62 })
63 .on('complete', function () {
64 console.log(
65 'Fastest is ' + LIST_FORMATTER.format(this.filter('fastest').map('name'))
66 )
67 // eslint-disable-next-line no-process-exit
68 process.exit()
69 })
70 .run()