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 runTest = async (pool, { taskExecutions, workerData }) => {
14 return new Promise((resolve, reject) => {
16 for (let i = 1; i <= taskExecutions; i++) {
21 if (executions === taskExecutions) {
22 return resolve({ ok: 1 })
34 export const generateRandomInteger = (
35 max = Number.MAX_SAFE_INTEGER,
38 if (max < min || max < 0 || min < 0) {
39 throw new RangeError('Invalid interval')
42 if (min != null && min !== 0) {
44 return Math.floor(Math.random() * (max - min + 1)) + min
46 return Math.floor(Math.random() * (max + 1))
49 const jsonIntegerSerialization = (n) => {
50 for (let i = 0; i < n; i++) {
60 * Intentionally inefficient implementation.
61 * @param {number} n - The number of fibonacci numbers to generate.
62 * @returns {number} - The nth fibonacci number.
64 const fibonacci = (n) => {
66 return fibonacci(n - 1) + fibonacci(n - 2)
70 * Intentionally inefficient implementation.
71 * @param {number} n - The number to calculate the factorial of.
72 * @returns {number} - The factorial of n.
74 const factorial = (n) => {
78 return factorial(n - 1) * n
81 const readWriteFiles = (
83 baseDirectory = `/tmp/poolifier-benchmarks/${crypto.randomInt(
87 if (fs.existsSync(baseDirectory) === true) {
88 fs.rmSync(baseDirectory, { recursive: true })
90 fs.mkdirSync(baseDirectory, { recursive: true })
91 for (let i = 0; i < n; i++) {
92 const filePath = `${baseDirectory}/${i}`
93 fs.writeFileSync(filePath, i.toString(), {
97 fs.readFileSync(filePath, 'utf8')
99 fs.rmSync(baseDirectory, { recursive: true })
103 export const executeTaskFunction = (data) => {
104 switch (data.function) {
105 case TaskFunctions.jsonIntegerSerialization:
106 return jsonIntegerSerialization(data.taskSize || 1000)
107 case TaskFunctions.fibonacci:
108 return fibonacci(data.taskSize || 1000)
109 case TaskFunctions.factorial:
110 return factorial(data.taskSize || 1000)
111 case TaskFunctions.readWriteFiles:
112 return readWriteFiles(data.taskSize || 1000)
114 throw new Error('Unknown task function')
118 export const buildPool = (workerType, poolType, poolSize, poolOptions) => {
120 case PoolTypes.fixed:
121 switch (workerType) {
122 case WorkerTypes.thread:
123 return new FixedThreadPool(
125 './benchmarks/internal/thread-worker.mjs',
128 case WorkerTypes.cluster:
129 return new FixedClusterPool(
131 './benchmarks/internal/cluster-worker.mjs',
136 case PoolTypes.dynamic:
137 switch (workerType) {
138 case WorkerTypes.thread:
139 return new DynamicThreadPool(
140 Math.floor(poolSize / 2),
142 './benchmarks/internal/thread-worker.mjs',
145 case WorkerTypes.cluster:
146 return new DynamicClusterPool(
147 Math.floor(poolSize / 2),
149 './benchmarks/internal/cluster-worker.mjs',