build(deps): bump poolifier
[poolifier.git] / benchmarks / benchmarks-utils.cjs
1 const { randomInt } = require('node:crypto')
2 const {
3 existsSync,
4 mkdirSync,
5 readFileSync,
6 rmSync,
7 writeFileSync
8 } = require('node:fs')
9 const { TaskFunctions } = require('./benchmarks-types.cjs')
10
11 const jsonIntegerSerialization = n => {
12 for (let i = 0; i < n; i++) {
13 const o = {
14 a: i
15 }
16 JSON.stringify(o)
17 }
18 return { ok: 1 }
19 }
20
21 /**
22 * @param {number} n - The number of fibonacci numbers to generate.
23 * @returns {number} - The nth fibonacci number.
24 */
25 const fibonacci = n => {
26 n = BigInt(n)
27 let current = 1n
28 let previous = 0n
29 while (--n) {
30 const tmp = current
31 current += previous
32 previous = tmp
33 }
34 // cluster worker do not support BigInt
35 return current.toString()
36 }
37
38 /**
39 * @param {number} n - The number to calculate the factorial of.
40 * @returns {number} - The factorial of n.
41 */
42 const factorial = n => {
43 if (n === 0 || n === 1) {
44 return 1n
45 } else {
46 n = BigInt(n)
47 let factorial = 1n
48 for (let i = 1n; i <= n; i++) {
49 factorial *= i
50 }
51 // cluster worker do not support BigInt
52 return factorial.toString()
53 }
54 }
55
56 const readWriteFiles = (
57 n,
58 baseDirectory = `/tmp/poolifier-benchmarks/${randomInt(281474976710655)}`
59 ) => {
60 if (existsSync(baseDirectory) === true) {
61 rmSync(baseDirectory, { recursive: true })
62 }
63 mkdirSync(baseDirectory, { recursive: true })
64 for (let i = 0; i < n; i++) {
65 const filePath = `${baseDirectory}/${i}`
66 writeFileSync(filePath, i.toString(), {
67 encoding: 'utf8',
68 flag: 'a'
69 })
70 readFileSync(filePath, 'utf8')
71 }
72 rmSync(baseDirectory, { recursive: true })
73 return { ok: 1 }
74 }
75
76 const executeTaskFunction = data => {
77 switch (data.function) {
78 case TaskFunctions.jsonIntegerSerialization:
79 return jsonIntegerSerialization(data.taskSize || 1000)
80 case TaskFunctions.fibonacci:
81 return fibonacci(data.taskSize || 1000)
82 case TaskFunctions.factorial:
83 return factorial(data.taskSize || 1000)
84 case TaskFunctions.readWriteFiles:
85 return readWriteFiles(data.taskSize || 1000)
86 default:
87 throw new Error('Unknown task function')
88 }
89 }
90
91 module.exports = {
92 executeTaskFunction
93 }