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