build(deps-dev): bump @types/node
[poolifier.git] / benchmarks / benchmarks-utils.js
CommitLineData
ab7bb4f8
JB
1const crypto = require('node:crypto')
2const assert = require('node:assert')
3const fs = require('node:fs')
4const Benchmark = require('benchmark')
5const {
cdace0e5
JB
6 DynamicClusterPool,
7 DynamicThreadPool,
8 FixedClusterPool,
d9d8c14e 9 FixedThreadPool,
617848e3 10 Measurements,
d9d8c14e 11 PoolTypes,
cde5b54e 12 WorkerChoiceStrategies,
d9d8c14e 13 WorkerTypes
ab7bb4f8
JB
14} = require('../lib/index.js')
15const { TaskFunctions } = require('./benchmarks-types.js')
2d2e32c2 16
ab7bb4f8 17const buildPoolifierPool = (workerType, poolType, poolSize, poolOptions) => {
479ba9f6
JB
18 switch (poolType) {
19 case PoolTypes.fixed:
20 switch (workerType) {
21 case WorkerTypes.thread:
22 return new FixedThreadPool(
23 poolSize,
24 './benchmarks/internal/thread-worker.mjs',
25 poolOptions
26 )
27 case WorkerTypes.cluster:
28 return new FixedClusterPool(
29 poolSize,
ab7bb4f8 30 './benchmarks/internal/cluster-worker.js',
479ba9f6
JB
31 poolOptions
32 )
33 }
34 break
35 case PoolTypes.dynamic:
36 switch (workerType) {
37 case WorkerTypes.thread:
38 return new DynamicThreadPool(
39 Math.floor(poolSize / 2),
40 poolSize,
41 './benchmarks/internal/thread-worker.mjs',
42 poolOptions
43 )
44 case WorkerTypes.cluster:
45 return new DynamicClusterPool(
46 Math.floor(poolSize / 2),
47 poolSize,
ab7bb4f8 48 './benchmarks/internal/cluster-worker.js',
479ba9f6
JB
49 poolOptions
50 )
51 }
52 break
53 }
54}
55
ab7bb4f8 56const runPoolifierPool = async (pool, { taskExecutions, workerData }) => {
cde5b54e 57 return await new Promise((resolve, reject) => {
ff5e76e1 58 let executions = 0
cdace0e5 59 for (let i = 1; i <= taskExecutions; i++) {
ff5e76e1
JB
60 pool
61 .execute(workerData)
fe2f6f84 62 .then(() => {
0762fbb1 63 ++executions
cdace0e5 64 if (executions === taskExecutions) {
cde5b54e 65 resolve({ ok: 1 })
ff5e76e1 66 }
fefd3cef 67 return undefined
ff5e76e1 68 })
041dc05b 69 .catch(err => {
23ff945a 70 console.error(err)
cde5b54e 71 reject(err)
23ff945a 72 })
ff5e76e1
JB
73 }
74 })
75}
76
ab7bb4f8 77const runPoolifierPoolBenchmark = async (
cde5b54e
JB
78 name,
79 pool,
80 { taskExecutions, workerData }
81) => {
82 return await new Promise((resolve, reject) => {
83 try {
84 const suite = new Benchmark.Suite(name)
85 for (const workerChoiceStrategy of Object.values(
86 WorkerChoiceStrategies
87 )) {
88 for (const enableTasksQueue of [false, true]) {
617848e3
JB
89 if (workerChoiceStrategy === WorkerChoiceStrategies.FAIR_SHARE) {
90 for (const measurement of [
91 Measurements.runTime,
92 Measurements.elu
93 ]) {
94 suite.add(
405896a3 95 `${name} with ${workerChoiceStrategy}, with ${measurement} and ${
617848e3
JB
96 enableTasksQueue ? 'with' : 'without'
97 } tasks queue`,
98 async () => {
99 pool.setWorkerChoiceStrategy(workerChoiceStrategy, {
100 measurement
101 })
102 pool.enableTasksQueue(enableTasksQueue)
103 assert.strictEqual(
104 pool.opts.workerChoiceStrategy,
105 workerChoiceStrategy
106 )
107 assert.strictEqual(
108 pool.opts.enableTasksQueue,
109 enableTasksQueue
110 )
111 assert.strictEqual(
112 pool.opts.workerChoiceStrategyOptions.measurement,
113 measurement
114 )
115 await runPoolifierPool(pool, {
116 taskExecutions,
117 workerData
118 })
119 }
cde5b54e 120 )
cde5b54e 121 }
617848e3
JB
122 } else {
123 suite.add(
405896a3 124 `${name} with ${workerChoiceStrategy} and ${
617848e3
JB
125 enableTasksQueue ? 'with' : 'without'
126 } tasks queue`,
127 async () => {
128 pool.setWorkerChoiceStrategy(workerChoiceStrategy)
129 pool.enableTasksQueue(enableTasksQueue)
130 assert.strictEqual(
131 pool.opts.workerChoiceStrategy,
132 workerChoiceStrategy
133 )
134 assert.strictEqual(pool.opts.enableTasksQueue, enableTasksQueue)
135 await runPoolifierPool(pool, {
136 taskExecutions,
137 workerData
138 })
139 }
140 )
141 }
cde5b54e
JB
142 }
143 }
144 suite
145 .on('cycle', event => {
146 console.info(event.target.toString())
147 })
148 .on('complete', async function () {
149 console.info(
150 'Fastest is ' +
151 LIST_FORMATTER.format(this.filter('fastest').map('name'))
152 )
153 await pool.destroy()
fefd3cef 154 pool = undefined
cde5b54e
JB
155 resolve()
156 })
157 .run({ async: true })
158 } catch (error) {
159 reject(error)
160 }
161 })
a7825346
JB
162}
163
ab7bb4f8 164const LIST_FORMATTER = new Intl.ListFormat('en-US', {
f1c674cd
JB
165 style: 'long',
166 type: 'conjunction'
167})
168
ab7bb4f8 169const generateRandomInteger = (max = Number.MAX_SAFE_INTEGER, min = 0) => {
548140e6 170 if (max < min || max < 0 || min < 0) {
4af5c11a
JB
171 throw new RangeError('Invalid interval')
172 }
c2d7d79b 173 max = Math.floor(max)
4af5c11a 174 if (min != null && min !== 0) {
c2d7d79b 175 min = Math.ceil(min)
872585ea 176 return Math.floor(Math.random() * (max - min + 1)) + min
74750c7f 177 }
872585ea 178 return Math.floor(Math.random() * (max + 1))
74750c7f
JB
179}
180
041dc05b 181const jsonIntegerSerialization = n => {
cdace0e5
JB
182 for (let i = 0; i < n; i++) {
183 const o = {
184 a: i
185 }
186 JSON.stringify(o)
187 }
30b963d4 188 return { ok: 1 }
cdace0e5
JB
189}
190
bdacc2d2
JB
191/**
192 * Intentionally inefficient implementation.
7d82d90e
JB
193 * @param {number} n - The number of fibonacci numbers to generate.
194 * @returns {number} - The nth fibonacci number.
bdacc2d2 195 */
041dc05b 196const fibonacci = n => {
024daf59 197 if (n <= 1) return n
bdacc2d2
JB
198 return fibonacci(n - 1) + fibonacci(n - 2)
199}
200
7d82d90e
JB
201/**
202 * Intentionally inefficient implementation.
7d82d90e
JB
203 * @param {number} n - The number to calculate the factorial of.
204 * @returns {number} - The factorial of n.
205 */
041dc05b 206const factorial = n => {
7d82d90e
JB
207 if (n === 0) {
208 return 1
7d82d90e 209 }
965415bb 210 return factorial(n - 1) * n
7d82d90e
JB
211}
212
bac873bd 213const readWriteFiles = (
670734fc
JB
214 n,
215 baseDirectory = `/tmp/poolifier-benchmarks/${crypto.randomInt(
216 281474976710655
217 )}`
bac873bd 218) => {
670734fc
JB
219 if (fs.existsSync(baseDirectory) === true) {
220 fs.rmSync(baseDirectory, { recursive: true })
cdace0e5 221 }
670734fc 222 fs.mkdirSync(baseDirectory, { recursive: true })
cdace0e5
JB
223 for (let i = 0; i < n; i++) {
224 const filePath = `${baseDirectory}/${i}`
225 fs.writeFileSync(filePath, i.toString(), {
226 encoding: 'utf8',
227 flag: 'a'
228 })
229 fs.readFileSync(filePath, 'utf8')
230 }
670734fc 231 fs.rmSync(baseDirectory, { recursive: true })
30b963d4 232 return { ok: 1 }
cdace0e5
JB
233}
234
ab7bb4f8 235const executeTaskFunction = data => {
2d2e32c2 236 switch (data.function) {
dbca3be9 237 case TaskFunctions.jsonIntegerSerialization:
d1a9aa41 238 return jsonIntegerSerialization(data.taskSize || 1000)
dbca3be9 239 case TaskFunctions.fibonacci:
d1a9aa41 240 return fibonacci(data.taskSize || 1000)
dbca3be9 241 case TaskFunctions.factorial:
d1a9aa41 242 return factorial(data.taskSize || 1000)
dbca3be9 243 case TaskFunctions.readWriteFiles:
cdace0e5 244 return readWriteFiles(data.taskSize || 1000)
2d2e32c2 245 default:
dbca3be9 246 throw new Error('Unknown task function')
2d2e32c2
JB
247 }
248}
ab7bb4f8
JB
249
250module.exports = {
251 LIST_FORMATTER,
252 buildPoolifierPool,
253 executeTaskFunction,
254 generateRandomInteger,
255 runPoolifierPoolBenchmark
256}