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