Switch internal benchmarking code to benny.
[poolifier.git] / benchmarks / benchmarks-utils.js
1 const { WorkerFunctions } = require('./benchmarks-types')
2
3 async 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
24 function jsonIntegerSerialization (n) {
25 for (let i = 0; i < n; i++) {
26 const o = {
27 a: i
28 }
29 JSON.stringify(o)
30 }
31 }
32
33 function generateRandomInteger (max = Number.MAX_SAFE_INTEGER, min = 0) {
34 max = Math.floor(max)
35 if (min) {
36 min = Math.ceil(min)
37 return Math.floor(Math.random() * (max - min + 1)) + min
38 }
39 return Math.floor(Math.random() * (max + 1))
40 }
41
42 /**
43 * Intentionally inefficient implementation.
44 *
45 * @param {number} n - The number of fibonacci numbers to generate.
46 * @returns {number} - The nth fibonacci number.
47 */
48 function fibonacci (n) {
49 if (n <= 1) return 1
50 return fibonacci(n - 1) + fibonacci(n - 2)
51 }
52
53 /**
54 * Intentionally inefficient implementation.
55 *
56 * @param {number} n - The number to calculate the factorial of.
57 * @returns {number} - The factorial of n.
58 */
59 function factorial (n) {
60 if (n === 0) {
61 return 1
62 } else {
63 return factorial(n - 1) * n
64 }
65 }
66
67 function executeWorkerFunction (data) {
68 switch (data.function) {
69 case WorkerFunctions.jsonIntegerSerialization:
70 return jsonIntegerSerialization(data.taskSize || 1000)
71 case WorkerFunctions.fibonacci:
72 return fibonacci(data.taskSize || 1000)
73 case WorkerFunctions.factorial:
74 return factorial(data.taskSize || 1000)
75 default:
76 throw new Error('Unknown worker function')
77 }
78 }
79
80 module.exports = {
81 WorkerFunctions,
82 executeWorkerFunction,
83 generateRandomInteger,
84 runPoolifierTest
85 }