Merge branch 'master' into combined-prs-branch
[poolifier.git] / benchmarks / worker-selection / round-robin.mjs
... / ...
CommitLineData
1import Benchmark from 'benchmark'
2import { LIST_FORMATTER } from '../benchmarks-utils.cjs'
3
4function generateWorkersArray (numberOfWorkers) {
5 return [...Array(numberOfWorkers).keys()]
6}
7
8const workers = generateWorkersArray(60)
9
10let nextWorkerIndex
11
12function roundRobinTernaryOffByOne () {
13 nextWorkerIndex =
14 workers.length - 1 === nextWorkerIndex ? 0 : nextWorkerIndex + 1
15 return workers[nextWorkerIndex]
16}
17
18function roundRobinTernaryWithNegation () {
19 nextWorkerIndex =
20 !nextWorkerIndex || workers.length - 1 === nextWorkerIndex
21 ? 0
22 : nextWorkerIndex + 1
23 return workers[nextWorkerIndex]
24}
25
26function roundRobinTernaryWithPreChoosing () {
27 const chosenWorker = workers[nextWorkerIndex]
28 nextWorkerIndex =
29 workers.length - 1 === nextWorkerIndex ? 0 : nextWorkerIndex + 1
30 return chosenWorker
31}
32
33function roundRobinIncrementModulo () {
34 const chosenWorker = workers[nextWorkerIndex]
35 nextWorkerIndex++
36 nextWorkerIndex %= workers.length
37 return chosenWorker
38}
39
40new Benchmark.Suite('Round robin tasks distribution')
41 .add('Ternary off by one', () => {
42 nextWorkerIndex = 0
43 roundRobinTernaryOffByOne()
44 })
45 .add('Ternary with negation', () => {
46 nextWorkerIndex = 0
47 roundRobinTernaryWithNegation()
48 })
49 .add('Ternary with pre-choosing', () => {
50 nextWorkerIndex = 0
51 roundRobinTernaryWithPreChoosing()
52 })
53 .add('Increment+Modulo', () => {
54 nextWorkerIndex = 0
55 roundRobinIncrementModulo()
56 })
57 .on('cycle', event => {
58 console.info(event.target.toString())
59 })
60 .on('complete', function () {
61 console.info(
62 'Fastest is ' + LIST_FORMATTER.format(this.filter('fastest').map('name'))
63 )
64 })
65 .run()