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++) {
58 * Intentionally inefficient implementation.
59 * @param {number} n - The number of fibonacci numbers to generate.
60 * @returns {number} - The nth fibonacci number.
62 const fibonacci = n => {
64 return fibonacci(n - 1) + fibonacci(n - 2)
68 * Intentionally inefficient implementation.
69 * @param {number} n - The number to calculate the factorial of.
70 * @returns {number} - The factorial of n.
72 const factorial = n => {
76 return factorial(n - 1) * n
79 const readWriteFiles = (
81 baseDirectory = `/tmp/poolifier-benchmarks/${crypto.randomInt(
85 if (fs.existsSync(baseDirectory) === true) {
86 fs.rmSync(baseDirectory, { recursive: true })
88 fs.mkdirSync(baseDirectory, { recursive: true })
89 for (let i = 0; i < n; i++) {
90 const filePath = `${baseDirectory}/${i}`
91 fs.writeFileSync(filePath, i.toString(), {
95 fs.readFileSync(filePath, 'utf8')
97 fs.rmSync(baseDirectory, { recursive: true })
101 export const executeWorkerFunction = data => {
102 switch (data.function) {
103 case WorkerFunctions.jsonIntegerSerialization:
104 return jsonIntegerSerialization(data.taskSize || 1000)
105 case WorkerFunctions.fibonacci:
106 return fibonacci(data.taskSize || 1000)
107 case WorkerFunctions.factorial:
108 return factorial(data.taskSize || 1000)
109 case WorkerFunctions.readWriteFiles:
110 return readWriteFiles(data.taskSize || 1000)
112 throw new Error('Unknown worker function')
116 export const buildPool = (workerType, poolType, poolSize, poolOptions) => {
118 case PoolTypes.fixed:
119 switch (workerType) {
120 case WorkerTypes.thread:
121 return new FixedThreadPool(
123 './benchmarks/internal/thread-worker.mjs',
126 case WorkerTypes.cluster:
127 return new FixedClusterPool(
129 './benchmarks/internal/cluster-worker.mjs',
134 case PoolTypes.dynamic:
135 switch (workerType) {
136 case WorkerTypes.thread:
137 return new DynamicThreadPool(
138 Math.floor(poolSize / 2),
140 './benchmarks/internal/thread-worker.mjs',
143 case WorkerTypes.cluster:
144 return new DynamicClusterPool(
145 Math.floor(poolSize / 2),
147 './benchmarks/internal/cluster-worker.mjs',