Add benchmark script (#104)
[poolifier.git] / benchmarks / bench.js
1 const Benchmark = require('benchmark')
2 const suite = new Benchmark.Suite()
3 const { FixedThreadPool } = require('../lib/index')
4 const { DynamicThreadPool } = require('../lib/index')
5 const size = 30
6 const tasks = 1
7
8 const LIST_FORMATTER = new Intl.ListFormat('en-US', {
9 style: 'long',
10 type: 'conjunction'
11 })
12
13 // pools
14 const fixedPool = new FixedThreadPool(size, './threadWorker.js', {
15 maxTasks: 10000
16 })
17 const dynamicPool = new DynamicThreadPool(
18 size / 2,
19 size * 3,
20 './threadWorker.js',
21 { maxTasks: 10000 }
22 )
23 const workerData = { proof: 'ok' }
24
25 // wait some seconds before start, my pools need to load threads !!!
26 setTimeout(async () => {
27 test()
28 }, 3000)
29
30 // fixed pool proof
31 async function fixedTest () {
32 return new Promise((resolve, reject) => {
33 let executions = 0
34 for (let i = 0; i <= tasks; i++) {
35 fixedPool
36 .execute(workerData)
37 .then(res => {
38 executions++
39 if (executions === tasks) {
40 return resolve('FINISH')
41 }
42 return null
43 })
44 .catch(err => {
45 console.error(err)
46 })
47 }
48 })
49 }
50
51 async function dynamicTest () {
52 return new Promise((resolve, reject) => {
53 let executions = 0
54 for (let i = 0; i <= tasks; i++) {
55 dynamicPool
56 .execute(workerData)
57 .then(res => {
58 executions++
59 if (executions === tasks) {
60 return resolve('FINISH')
61 }
62 return null
63 })
64 .catch(err => console.error(err))
65 }
66 })
67 }
68
69 async function test () {
70 // add tests
71 suite
72 .add('PioardiStaticPool', async function () {
73 await fixedTest()
74 })
75 .add('PioardiDynamicPool', async function () {
76 await dynamicTest()
77 })
78 // add listeners
79 .on('cycle', function (event) {
80 console.log(event.target.toString())
81 })
82 .on('complete', function () {
83 console.log(
84 'Fastest is ' +
85 LIST_FORMATTER.format(this.filter('fastest').map('name'))
86 )
87 // eslint-disable-next-line no-process-exit
88 process.exit()
89 })
90 // run async
91 .run({ async: true })
92 }