-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbusy-wait.mjs
79 lines (71 loc) · 1.74 KB
/
busy-wait.mjs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
import { bench, group, run } from 'tatami-ng'
import { sleep } from './benchmark-utils.mjs'
const timeout = 2000
const interval = 1000
/**
* @param timeoutMs
* @param intervalMs
*/
async function divideAndConquerTimeoutBusyWait (
timeoutMs,
intervalMs = interval
) {
const tries = Math.round(timeoutMs / intervalMs)
let count = 0
do {
count++
await sleep(intervalMs)
} while (count <= tries)
}
/**
* @param timeoutMs
*/
function dummyTimeoutBusyWait (timeoutMs) {
const timeoutTimestampMs = performance.now() + timeoutMs
// eslint-disable-next-line no-empty
do {} while (performance.now() < timeoutTimestampMs)
}
/**
* @param timeoutMs
* @param intervalMs
*/
async function setIntervalTimeoutBusyWait (timeoutMs, intervalMs = interval) {
await new Promise(resolve => {
const tries = Math.round(timeoutMs / intervalMs)
let count = 0
const triesSetInterval = setInterval(() => {
count++
if (count === tries) {
clearInterval(triesSetInterval)
resolve()
}
}, intervalMs)
})
}
/**
* @param timeoutMs
* @param intervalMs
*/
async function sleepTimeoutBusyWait (timeoutMs, intervalMs = interval) {
const timeoutTimestampMs = performance.now() + timeoutMs
do {
await sleep(intervalMs)
} while (performance.now() < timeoutTimestampMs)
}
group('Busy wait', () => {
bench('dummyTimeoutBusyWait', () => {
dummyTimeoutBusyWait(timeout)
})
bench('sleepTimeoutBusyWait', async () => {
await sleepTimeoutBusyWait(timeout)
})
bench('divideAndConquerTimeoutBusyWait', async () => {
await divideAndConquerTimeoutBusyWait(timeout)
})
bench('setIntervalTimeoutBusyWait', async () => {
await setIntervalTimeoutBusyWait(timeout)
})
})
await run({
units: true,
})