75b44e22 |
1 | const FixedThreadPool = require('../lib/fixed') |
2 | const DynamicThreadPool = require('../lib/dynamic') |
3 | const Pool = require('worker-threads-pool') |
4 | const tasks = 1000 |
106744f7 |
5 | const size = 16 |
75b44e22 |
6 | |
7 | // pools |
8 | const externalPool = new Pool({ max: size }) |
9 | const fixedPool = new FixedThreadPool(size, './yourWorker.js', { maxTasks: 10000 }) |
106744f7 |
10 | const dynamicPool = new DynamicThreadPool(size / 2, size * 3, './yourWorker.js', { maxTasks: 10000 }) |
75b44e22 |
11 | |
12 | // data |
13 | const workerData = { proof: 'ok' } |
14 | |
15 | // fixed pool proof |
16 | async function fixedTest () { |
17 | let executions = 0 |
18 | const time = Date.now() |
8d9ce260 |
19 | for (let i = 0; i <= tasks; i++) { |
20 | fixedPool.execute(workerData).then(res => { |
21 | executions++ |
22 | if (executions === tasks) console.log(`Fixed pool take ${Date.now() - time} to work on ${executions} tasks`) |
23 | }) |
75b44e22 |
24 | } |
75b44e22 |
25 | } |
26 | |
27 | async function dynamicTest () { |
28 | let executions = 0 |
29 | const time = Date.now() |
8d9ce260 |
30 | for (let i = 0; i <= tasks; i++) { |
31 | dynamicPool.execute(workerData).then(res => { |
32 | executions++ |
33 | if (executions === tasks) console.log(`Dynamic pool take ${Date.now() - time} to work on ${executions} tasks`) |
34 | }) |
75b44e22 |
35 | } |
75b44e22 |
36 | } |
37 | |
38 | async function externalPoolTest () { |
39 | let executions = 0 |
40 | const time = Date.now() |
8d9ce260 |
41 | for (let i = 0; i <= tasks; i++) { |
42 | new Promise((resolve, reject) => { |
75b44e22 |
43 | externalPool.acquire('./externalWorker.js', { workerData: workerData }, (err, worker) => { |
44 | if (err) { |
45 | return reject(err) |
46 | } |
47 | worker.on('error', reject) |
48 | worker.on('message', res => { |
49 | executions++ |
50 | resolve(res) |
51 | }) |
52 | }) |
8d9ce260 |
53 | }).then(res => { |
54 | if (tasks === executions) console.log(`External pool take ${Date.now() - time} to work on ${executions} tasks`) |
75b44e22 |
55 | }) |
56 | } |
75b44e22 |
57 | } |
58 | |
59 | async function test () { |
8d9ce260 |
60 | fixedTest() |
61 | dynamicTest() |
62 | externalPoolTest() |
75b44e22 |
63 | } |
64 | |
65 | test() |