Commit | Line | Data |
---|---|---|
ed2968f2 | 1 | const Benchmark = require('benchmark') |
a9c78d5d | 2 | const { LIST_FORMATTER, sleep } = require('./benchmark-utils') |
ed2968f2 JB |
3 | |
4 | const suite = new Benchmark.Suite() | |
5 | ||
6 | const timeout = 2000 | |
a8bf8b7d | 7 | const interval = 1000 |
ed2968f2 | 8 | |
a6c34381 JB |
9 | /** |
10 | * @param timeoutMs | |
11 | */ | |
12 | function 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 | 21 | async 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 |
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 | */ |
a8bf8b7d | 48 | function 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 | ||
59 | suite | |
a6c34381 JB |
60 | .add('dummyTimeoutBusyWait', function () { |
61 | dummyTimeoutBusyWait(timeout) | |
62 | }) | |
a8bf8b7d JB |
63 | .add('sleepTimeoutBusyWait', async function () { |
64 | sleepTimeoutBusyWait(timeout) | |
ed2968f2 | 65 | }) |
a9c78d5d JB |
66 | .add('divideAndConquerTimeoutBusyWait', async function () { |
67 | await divideAndConquerTimeoutBusyWait(timeout) | |
68 | }) | |
ed2968f2 JB |
69 | .add('setIntervalTimeoutBusyWait', function () { |
70 | setIntervalTimeoutBusyWait(timeout) | |
71 | }) | |
72 | .on('cycle', function (event) { | |
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() |