Commit | Line | Data |
---|---|---|
4676a95c | 1 | import { bench, group, run } from 'tatami-ng' |
0c01f51c | 2 | |
95d31631 | 3 | import { sleep } from './benchmark-utils.mjs' |
ed2968f2 JB |
4 | |
5 | const timeout = 2000 | |
a8bf8b7d | 6 | const interval = 1000 |
ed2968f2 | 7 | |
a6c34381 JB |
8 | /** |
9 | * @param timeoutMs | |
10 | */ | |
11 | function dummyTimeoutBusyWait (timeoutMs) { | |
41672b12 | 12 | const timeoutTimestampMs = performance.now() + timeoutMs |
7fd91296 | 13 | // eslint-disable-next-line no-empty |
41672b12 | 14 | do {} while (performance.now() < timeoutTimestampMs) |
a6c34381 JB |
15 | } |
16 | ||
e9bfc28e JB |
17 | /** |
18 | * @param timeoutMs | |
eab47c66 | 19 | * @param intervalMs |
e9bfc28e | 20 | */ |
eab47c66 | 21 | async function sleepTimeoutBusyWait (timeoutMs, intervalMs = interval) { |
41672b12 | 22 | const timeoutTimestampMs = performance.now() + timeoutMs |
a8bf8b7d | 23 | do { |
eab47c66 | 24 | await sleep(intervalMs) |
41672b12 | 25 | } while (performance.now() < timeoutTimestampMs) |
a9c78d5d JB |
26 | } |
27 | ||
28 | /** | |
29 | * @param timeoutMs | |
e47f67db | 30 | * @param intervalMs |
a9c78d5d | 31 | */ |
a8bf8b7d JB |
32 | async 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 | */ |
eab47c66 | 48 | async function setIntervalTimeoutBusyWait (timeoutMs, intervalMs = interval) { |
bcd364e0 | 49 | await new Promise(resolve => { |
1652efb2 JB |
50 | const tries = Math.round(timeoutMs / intervalMs) |
51 | let count = 0 | |
52 | const triesSetInterval = setInterval(() => { | |
53 | count++ | |
54 | if (count === tries) { | |
55 | clearInterval(triesSetInterval) | |
bcd364e0 | 56 | resolve() |
1652efb2 JB |
57 | } |
58 | }, intervalMs) | |
59 | }) | |
ed2968f2 JB |
60 | } |
61 | ||
ab9a08f3 JB |
62 | group('Busy wait', () => { |
63 | bench('dummyTimeoutBusyWait', () => { | |
a6c34381 | 64 | dummyTimeoutBusyWait(timeout) |
ab9a08f3 JB |
65 | }) |
66 | bench('sleepTimeoutBusyWait', async () => { | |
ed40d2b0 | 67 | await sleepTimeoutBusyWait(timeout) |
ab9a08f3 JB |
68 | }) |
69 | bench('divideAndConquerTimeoutBusyWait', async () => { | |
a9c78d5d | 70 | await divideAndConquerTimeoutBusyWait(timeout) |
ab9a08f3 JB |
71 | }) |
72 | bench('setIntervalTimeoutBusyWait', async () => { | |
eab47c66 | 73 | await setIntervalTimeoutBusyWait(timeout) |
ab9a08f3 JB |
74 | }) |
75 | }) | |
76 | ||
77 | await run({ | |
ebf80fe4 | 78 | units: true, |
ab9a08f3 | 79 | }) |