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 LIST_FORMATTER = new Intl.ListFormat('en-US', {
86 export const executeAsyncFn = async fn => {
91 // eslint-disable-next-line n/no-process-exit
96 export const generateRandomInteger = (
97 max = Number.MAX_SAFE_INTEGER,
100 if (max < min || max < 0 || min < 0) {
101 throw new RangeError('Invalid interval')
103 max = Math.floor(max)
104 if (min != null && min !== 0) {
106 return Math.floor(Math.random() * (max - min + 1)) + min
108 return Math.floor(Math.random() * (max + 1))
111 const jsonIntegerSerialization = n => {
112 for (let i = 0; i < n; i++) {
122 * Intentionally inefficient implementation.
123 * @param {number} n - The number of fibonacci numbers to generate.
124 * @returns {number} - The nth fibonacci number.
126 const fibonacci = n => {
128 return fibonacci(n - 1) + fibonacci(n - 2)
132 * Intentionally inefficient implementation.
133 * @param {number} n - The number to calculate the factorial of.
134 * @returns {number} - The factorial of n.
136 const factorial = n => {
140 return factorial(n - 1) * n
143 const readWriteFiles = (
145 baseDirectory = `/tmp/poolifier-benchmarks/${crypto.randomInt(
149 if (fs.existsSync(baseDirectory) === true) {
150 fs.rmSync(baseDirectory, { recursive: true })
152 fs.mkdirSync(baseDirectory, { recursive: true })
153 for (let i = 0; i < n; i++) {
154 const filePath = `${baseDirectory}/${i}`
155 fs.writeFileSync(filePath, i.toString(), {
159 fs.readFileSync(filePath, 'utf8')
161 fs.rmSync(baseDirectory, { recursive: true })
165 export const executeTaskFunction = data => {
166 switch (data.function) {
167 case TaskFunctions.jsonIntegerSerialization:
168 return jsonIntegerSerialization(data.taskSize || 1000)
169 case TaskFunctions.fibonacci:
170 return fibonacci(data.taskSize || 1000)
171 case TaskFunctions.factorial:
172 return factorial(data.taskSize || 1000)
173 case TaskFunctions.readWriteFiles:
174 return readWriteFiles(data.taskSize || 1000)
176 throw new Error('Unknown task function')