1 import crypto from 'node:crypto'
2 import fs from 'node:fs'
10 } from '../lib/index.mjs'
11 import { TaskFunctions } from './benchmarks-types.mjs'
13 export const buildPoolifierPool = (
22 case WorkerTypes.thread:
23 return new FixedThreadPool(
25 './benchmarks/internal/thread-worker.mjs',
28 case WorkerTypes.cluster:
29 return new FixedClusterPool(
31 './benchmarks/internal/cluster-worker.mjs',
36 case PoolTypes.dynamic:
38 case WorkerTypes.thread:
39 return new DynamicThreadPool(
40 Math.floor(poolSize / 2),
42 './benchmarks/internal/thread-worker.mjs',
45 case WorkerTypes.cluster:
46 return new DynamicClusterPool(
47 Math.floor(poolSize / 2),
49 './benchmarks/internal/cluster-worker.mjs',
57 export const runPoolifierTest = async (
59 { taskExecutions, workerData }
61 return new Promise((resolve, reject) => {
63 for (let i = 1; i <= taskExecutions; i++) {
68 if (executions === taskExecutions) {
69 return resolve({ ok: 1 })
81 export const executeAsyncFn = async fn => {
86 // eslint-disable-next-line n/no-process-exit
91 export const generateRandomInteger = (
92 max = Number.MAX_SAFE_INTEGER,
95 if (max < min || max < 0 || min < 0) {
96 throw new RangeError('Invalid interval')
99 if (min != null && min !== 0) {
101 return Math.floor(Math.random() * (max - min + 1)) + min
103 return Math.floor(Math.random() * (max + 1))
106 const jsonIntegerSerialization = n => {
107 for (let i = 0; i < n; i++) {
117 * Intentionally inefficient implementation.
118 * @param {number} n - The number of fibonacci numbers to generate.
119 * @returns {number} - The nth fibonacci number.
121 const fibonacci = n => {
123 return fibonacci(n - 1) + fibonacci(n - 2)
127 * Intentionally inefficient implementation.
128 * @param {number} n - The number to calculate the factorial of.
129 * @returns {number} - The factorial of n.
131 const factorial = n => {
135 return factorial(n - 1) * n
138 const readWriteFiles = (
140 baseDirectory = `/tmp/poolifier-benchmarks/${crypto.randomInt(
144 if (fs.existsSync(baseDirectory) === true) {
145 fs.rmSync(baseDirectory, { recursive: true })
147 fs.mkdirSync(baseDirectory, { recursive: true })
148 for (let i = 0; i < n; i++) {
149 const filePath = `${baseDirectory}/${i}`
150 fs.writeFileSync(filePath, i.toString(), {
154 fs.readFileSync(filePath, 'utf8')
156 fs.rmSync(baseDirectory, { recursive: true })
160 export const executeTaskFunction = data => {
161 switch (data.function) {
162 case TaskFunctions.jsonIntegerSerialization:
163 return jsonIntegerSerialization(data.taskSize || 1000)
164 case TaskFunctions.fibonacci:
165 return fibonacci(data.taskSize || 1000)
166 case TaskFunctions.factorial:
167 return factorial(data.taskSize || 1000)
168 case TaskFunctions.readWriteFiles:
169 return readWriteFiles(data.taskSize || 1000)
171 throw new Error('Unknown task function')