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