| 1 | const Benchmark = require('benchmark') |
| 2 | const { LIST_FORMATTER, sleep } = require('./benchmark-utils') |
| 3 | |
| 4 | const suite = new Benchmark.Suite() |
| 5 | |
| 6 | const timeout = 2000 |
| 7 | const interval = 1000 |
| 8 | |
| 9 | /** |
| 10 | * @param timeoutMs |
| 11 | */ |
| 12 | function dummyTimeoutBusyWait (timeoutMs) { |
| 13 | const timeoutTimestampMs = Date.now() + timeoutMs |
| 14 | // eslint-disable-next-line no-empty |
| 15 | do {} while (Date.now() < timeoutTimestampMs) |
| 16 | } |
| 17 | |
| 18 | /** |
| 19 | * @param timeoutMs |
| 20 | */ |
| 21 | async function sleepTimeoutBusyWait (timeoutMs) { |
| 22 | const timeoutTimestampMs = Date.now() + timeoutMs |
| 23 | do { |
| 24 | await sleep(interval) |
| 25 | } while (Date.now() < timeoutTimestampMs) |
| 26 | } |
| 27 | |
| 28 | /** |
| 29 | * @param timeoutMs |
| 30 | * @param intervalMs |
| 31 | */ |
| 32 | async function divideAndConquerTimeoutBusyWait ( |
| 33 | timeoutMs, |
| 34 | intervalMs = interval |
| 35 | ) { |
| 36 | const tries = Math.round(timeoutMs / intervalMs) |
| 37 | let count = 0 |
| 38 | do { |
| 39 | count++ |
| 40 | await sleep(intervalMs) |
| 41 | } while (count <= tries) |
| 42 | } |
| 43 | |
| 44 | /** |
| 45 | * @param timeoutMs |
| 46 | * @param intervalMs |
| 47 | */ |
| 48 | function setIntervalTimeoutBusyWait (timeoutMs, intervalMs = interval) { |
| 49 | const tries = Math.round(timeoutMs / intervalMs) |
| 50 | let count = 0 |
| 51 | const triesSetInterval = setInterval(() => { |
| 52 | count++ |
| 53 | if (count === tries) { |
| 54 | clearInterval(triesSetInterval) |
| 55 | } |
| 56 | }, intervalMs) |
| 57 | } |
| 58 | |
| 59 | suite |
| 60 | .add('dummyTimeoutBusyWait', function () { |
| 61 | dummyTimeoutBusyWait(timeout) |
| 62 | }) |
| 63 | .add('sleepTimeoutBusyWait', async function () { |
| 64 | sleepTimeoutBusyWait(timeout) |
| 65 | }) |
| 66 | .add('divideAndConquerTimeoutBusyWait', async function () { |
| 67 | await divideAndConquerTimeoutBusyWait(timeout) |
| 68 | }) |
| 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 | ) |
| 79 | // eslint-disable-next-line n/no-process-exit |
| 80 | process.exit() |
| 81 | }) |
| 82 | .run() |