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