Merge branch 'master' of github.com:poolifier/poolifier
[poolifier.git] / benchmarks / benchmarks-utils.js
CommitLineData
e4bc7a49 1const { WorkerFunctions } = require('./benchmarks-types')
2d2e32c2 2
74750c7f 3async function runPoolifierTest (pool, { tasks, workerData }) {
ff5e76e1
JB
4 return new Promise((resolve, reject) => {
5 let executions = 0
292ad316 6 for (let i = 1; i <= tasks; i++) {
ff5e76e1
JB
7 pool
8 .execute(workerData)
fe2f6f84 9 .then(() => {
ff5e76e1
JB
10 executions++
11 if (executions === tasks) {
ca6c7d70 12 return resolve({ ok: 1 })
ff5e76e1
JB
13 }
14 return null
15 })
23ff945a
JB
16 .catch(err => {
17 console.error(err)
18 return reject(err)
19 })
ff5e76e1
JB
20 }
21 })
22}
23
bdacc2d2
JB
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
9bc18a6d 33function generateRandomInteger (max = Number.MAX_SAFE_INTEGER, min = 0) {
548140e6 34 if (max < min || max < 0 || min < 0) {
4af5c11a
JB
35 throw new RangeError('Invalid interval')
36 }
c2d7d79b 37 max = Math.floor(max)
4af5c11a 38 if (min != null && min !== 0) {
c2d7d79b 39 min = Math.ceil(min)
872585ea 40 return Math.floor(Math.random() * (max - min + 1)) + min
74750c7f 41 }
872585ea 42 return Math.floor(Math.random() * (max + 1))
74750c7f
JB
43}
44
bdacc2d2
JB
45/**
46 * Intentionally inefficient implementation.
47 *
7d82d90e
JB
48 * @param {number} n - The number of fibonacci numbers to generate.
49 * @returns {number} - The nth fibonacci number.
bdacc2d2
JB
50 */
51function fibonacci (n) {
52 if (n <= 1) return 1
53 return fibonacci(n - 1) + fibonacci(n - 2)
54}
55
7d82d90e
JB
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 } else {
66 return factorial(n - 1) * n
67 }
68}
69
2d2e32c2
JB
70function executeWorkerFunction (data) {
71 switch (data.function) {
72 case WorkerFunctions.jsonIntegerSerialization:
d1a9aa41 73 return jsonIntegerSerialization(data.taskSize || 1000)
2d2e32c2 74 case WorkerFunctions.fibonacci:
d1a9aa41 75 return fibonacci(data.taskSize || 1000)
2d2e32c2 76 case WorkerFunctions.factorial:
d1a9aa41 77 return factorial(data.taskSize || 1000)
2d2e32c2
JB
78 default:
79 throw new Error('Unknown worker function')
80 }
81}
82
bdacc2d2 83module.exports = {
2d2e32c2
JB
84 WorkerFunctions,
85 executeWorkerFunction,
bdacc2d2 86 generateRandomInteger,
2d2e32c2 87 runPoolifierTest
bdacc2d2 88}