1 import crypto from 'crypto'
8 } from '../lib/index.mjs'
9 import { PoolTypes, WorkerFunctions, WorkerTypes } from './benchmarks-types.mjs'
11 export async function runTest (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 function generateRandomInteger (max = Number.MAX_SAFE_INTEGER, min = 0) {
33 if (max < min || max < 0 || min < 0) {
34 throw new RangeError('Invalid interval')
37 if (min != null && min !== 0) {
39 return Math.floor(Math.random() * (max - min + 1)) + min
41 return Math.floor(Math.random() * (max + 1))
44 function jsonIntegerSerialization (n) {
45 for (let i = 0; i < n; i++) {
54 * Intentionally inefficient implementation.
55 * @param {number} n - The number of fibonacci numbers to generate.
56 * @returns {number} - The nth fibonacci number.
58 function fibonacci (n) {
60 return fibonacci(n - 1) + fibonacci(n - 2)
64 * Intentionally inefficient implementation.
65 * @param {number} n - The number to calculate the factorial of.
66 * @returns {number} - The factorial of n.
68 function factorial (n) {
72 return factorial(n - 1) * n
75 function readWriteFiles (
77 baseDirectory = `/tmp/poolifier-benchmarks/${crypto.randomInt(
81 if (fs.existsSync(baseDirectory) === true) {
82 fs.rmSync(baseDirectory, { recursive: true })
84 fs.mkdirSync(baseDirectory, { recursive: true })
85 for (let i = 0; i < n; i++) {
86 const filePath = `${baseDirectory}/${i}`
87 fs.writeFileSync(filePath, i.toString(), {
91 fs.readFileSync(filePath, 'utf8')
93 fs.rmSync(baseDirectory, { recursive: true })
96 export function executeWorkerFunction (data) {
97 switch (data.function) {
98 case WorkerFunctions.jsonIntegerSerialization:
99 return jsonIntegerSerialization(data.taskSize || 1000)
100 case WorkerFunctions.fibonacci:
101 return fibonacci(data.taskSize || 1000)
102 case WorkerFunctions.factorial:
103 return factorial(data.taskSize || 1000)
104 case WorkerFunctions.readWriteFiles:
105 return readWriteFiles(data.taskSize || 1000)
107 throw new Error('Unknown worker function')
111 export function buildPool (workerType, poolType, poolSize, poolOptions) {
113 case PoolTypes.fixed:
114 switch (workerType) {
115 case WorkerTypes.thread:
116 return new FixedThreadPool(
118 './benchmarks/internal/thread-worker.mjs',
121 case WorkerTypes.cluster:
122 return new FixedClusterPool(
124 './benchmarks/internal/cluster-worker.mjs',
129 case PoolTypes.dynamic:
130 switch (workerType) {
131 case WorkerTypes.thread:
132 return new DynamicThreadPool(
135 './benchmarks/internal/thread-worker.mjs',
138 case WorkerTypes.cluster:
139 return new DynamicClusterPool(
142 './benchmarks/internal/cluster-worker.mjs',