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