1 import crypto from 'crypto'
8 } from '../lib/index.mjs'
9 import { PoolTypes, WorkerFunctions, WorkerTypes } from './benchmarks-types.mjs'
11 export const runTest = async (pool, { taskExecutions, workerData }) => {
12 return new Promise((resolve, reject) => {
14 for (let i = 1; i <= taskExecutions; i++) {
19 if (executions === taskExecutions) {
20 return resolve({ ok: 1 })
32 export const generateRandomInteger = (
33 max = Number.MAX_SAFE_INTEGER,
36 if (max < min || max < 0 || min < 0) {
37 throw new RangeError('Invalid interval')
40 if (min != null && min !== 0) {
42 return Math.floor(Math.random() * (max - min + 1)) + min
44 return Math.floor(Math.random() * (max + 1))
47 const jsonIntegerSerialization = n => {
48 for (let i = 0; i < n; i++) {
57 * Intentionally inefficient implementation.
58 * @param {number} n - The number of fibonacci numbers to generate.
59 * @returns {number} - The nth fibonacci number.
61 const fibonacci = n => {
63 return fibonacci(n - 1) + fibonacci(n - 2)
67 * Intentionally inefficient implementation.
68 * @param {number} n - The number to calculate the factorial of.
69 * @returns {number} - The factorial of n.
71 const factorial = n => {
75 return factorial(n - 1) * n
78 const readWriteFiles = (
80 baseDirectory = `/tmp/poolifier-benchmarks/${crypto.randomInt(
84 if (fs.existsSync(baseDirectory) === true) {
85 fs.rmSync(baseDirectory, { recursive: true })
87 fs.mkdirSync(baseDirectory, { recursive: true })
88 for (let i = 0; i < n; i++) {
89 const filePath = `${baseDirectory}/${i}`
90 fs.writeFileSync(filePath, i.toString(), {
94 fs.readFileSync(filePath, 'utf8')
96 fs.rmSync(baseDirectory, { recursive: true })
99 export const executeWorkerFunction = data => {
100 switch (data.function) {
101 case WorkerFunctions.jsonIntegerSerialization:
102 return jsonIntegerSerialization(data.taskSize || 1000)
103 case WorkerFunctions.fibonacci:
104 return fibonacci(data.taskSize || 1000)
105 case WorkerFunctions.factorial:
106 return factorial(data.taskSize || 1000)
107 case WorkerFunctions.readWriteFiles:
108 return readWriteFiles(data.taskSize || 1000)
110 throw new Error('Unknown worker function')
114 export const buildPool = (workerType, poolType, poolSize, poolOptions) => {
116 case PoolTypes.fixed:
117 switch (workerType) {
118 case WorkerTypes.thread:
119 return new FixedThreadPool(
121 './benchmarks/internal/thread-worker.mjs',
124 case WorkerTypes.cluster:
125 return new FixedClusterPool(
127 './benchmarks/internal/cluster-worker.mjs',
132 case PoolTypes.dynamic:
133 switch (workerType) {
134 case WorkerTypes.thread:
135 return new DynamicThreadPool(
136 Math.floor(poolSize / 2),
138 './benchmarks/internal/thread-worker.mjs',
141 case WorkerTypes.cluster:
142 return new DynamicClusterPool(
143 Math.floor(poolSize / 2),
145 './benchmarks/internal/cluster-worker.mjs',