perf: remove unneeded class indirection for dynamic pool in worker
[poolifier.git] / benchmarks / benchmarks-utils.js
... / ...
CommitLineData
1const { WorkerFunctions } = require('./benchmarks-types')
2
3async function runPoolifierTest (pool, { tasks, workerData }) {
4 return new Promise((resolve, reject) => {
5 let executions = 0
6 for (let i = 1; i <= tasks; i++) {
7 pool
8 .execute(workerData)
9 .then(() => {
10 executions++
11 if (executions === tasks) {
12 return resolve({ ok: 1 })
13 }
14 return null
15 })
16 .catch(err => {
17 console.error(err)
18 return reject(err)
19 })
20 }
21 })
22}
23
24function jsonIntegerSerialization (n) {
25 for (let i = 0; i < n; i++) {
26 const o = {
27 a: i
28 }
29 JSON.stringify(o)
30 }
31}
32
33function generateRandomInteger (max = Number.MAX_SAFE_INTEGER, min = 0) {
34 if (max < min || max < 0 || min < 0) {
35 throw new RangeError('Invalid interval')
36 }
37 max = Math.floor(max)
38 if (min != null && min !== 0) {
39 min = Math.ceil(min)
40 return Math.floor(Math.random() * (max - min + 1)) + min
41 }
42 return Math.floor(Math.random() * (max + 1))
43}
44
45/**
46 * Intentionally inefficient implementation.
47 *
48 * @param {number} n - The number of fibonacci numbers to generate.
49 * @returns {number} - The nth fibonacci number.
50 */
51function fibonacci (n) {
52 if (n <= 1) return 1
53 return fibonacci(n - 1) + fibonacci(n - 2)
54}
55
56/**
57 * Intentionally inefficient implementation.
58 *
59 * @param {number} n - The number to calculate the factorial of.
60 * @returns {number} - The factorial of n.
61 */
62function factorial (n) {
63 if (n === 0) {
64 return 1
65 }
66 return factorial(n - 1) * n
67}
68
69function executeWorkerFunction (data) {
70 switch (data.function) {
71 case WorkerFunctions.jsonIntegerSerialization:
72 return jsonIntegerSerialization(data.taskSize || 1000)
73 case WorkerFunctions.fibonacci:
74 return fibonacci(data.taskSize || 1000)
75 case WorkerFunctions.factorial:
76 return factorial(data.taskSize || 1000)
77 default:
78 throw new Error('Unknown worker function')
79 }
80}
81
82module.exports = {
83 WorkerFunctions,
84 executeWorkerFunction,
85 generateRandomInteger,
86 runPoolifierTest
87}