busy-wait.js: rename a method argument
[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
8 /**
9 * @param timeoutMs
10 */
11 function dummyTimeoutBusyWait (timeoutMs) {
12 const timeoutTimestampMs = Date.now() + timeoutMs
13 do {} while (Date.now() < timeoutTimestampMs)
14 }
15
16 /**
17 * @param timeoutMs
18 * @param intervalMs
19 */
20 async function divideAndConquerTimeoutBusyWait (timeoutMs, intervalMs = 200) {
21 const tries = Math.round(timeoutMs / intervalMs)
22 let count = 0
23 do {
24 count++
25 await sleep(intervalMs)
26 } while (count <= tries)
27 }
28
29 /**
30 * @param timeoutMs
31 * @param intervalMs
32 */
33 function setIntervalTimeoutBusyWait (timeoutMs, intervalMs = 200) {
34 const tries = Math.round(timeoutMs / intervalMs)
35 let count = 0
36 const triesSetInterval = setInterval(() => {
37 count++
38 if (count === tries) {
39 clearInterval(triesSetInterval)
40 }
41 }, intervalMs)
42 }
43
44 suite
45 .add('dummyTimeoutBusyWait', function () {
46 dummyTimeoutBusyWait(timeout)
47 })
48 .add('divideAndConquerTimeoutBusyWait', async function () {
49 await divideAndConquerTimeoutBusyWait(timeout)
50 })
51 .add('setIntervalTimeoutBusyWait', function () {
52 setIntervalTimeoutBusyWait(timeout)
53 })
54 .on('cycle', function (event) {
55 console.log(event.target.toString())
56 })
57 .on('complete', function () {
58 console.log(
59 'Fastest is ' + LIST_FORMATTER.format(this.filter('fastest').map('name'))
60 )
61 // eslint-disable-next-line no-process-exit
62 process.exit()
63 })
64 .run()