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 }) |
cf9aa6c3 |
9 | const fixedPool = new FixedThreadPool(size, './yourWorker.js', { |
10 | maxTasks: 10000 |
11 | }) |
12 | const dynamicPool = new DynamicThreadPool( |
13 | size / 2, |
14 | size * 3, |
15 | './yourWorker.js', |
16 | { maxTasks: 10000 } |
17 | ) |
75b44e22 |
18 | |
19 | // data |
20 | const workerData = { proof: 'ok' } |
21 | |
22 | // fixed pool proof |
23 | async function fixedTest () { |
24 | let executions = 0 |
25 | const time = Date.now() |
8d9ce260 |
26 | for (let i = 0; i <= tasks; i++) { |
27 | fixedPool.execute(workerData).then(res => { |
28 | executions++ |
cf9aa6c3 |
29 | if (executions === tasks) { |
30 | console.log( |
31 | `Fixed pool take ${Date.now() - time} to work on ${executions} tasks` |
32 | ) |
33 | } |
8d9ce260 |
34 | }) |
75b44e22 |
35 | } |
75b44e22 |
36 | } |
37 | |
38 | async function dynamicTest () { |
39 | let executions = 0 |
40 | const time = Date.now() |
8d9ce260 |
41 | for (let i = 0; i <= tasks; i++) { |
42 | dynamicPool.execute(workerData).then(res => { |
43 | executions++ |
cf9aa6c3 |
44 | if (executions === tasks) { |
45 | console.log( |
46 | `Dynamic pool take ${Date.now() - |
47 | time} to work on ${executions} tasks` |
48 | ) |
49 | } |
8d9ce260 |
50 | }) |
75b44e22 |
51 | } |
75b44e22 |
52 | } |
53 | |
54 | async function externalPoolTest () { |
55 | let executions = 0 |
56 | const time = Date.now() |
8d9ce260 |
57 | for (let i = 0; i <= tasks; i++) { |
58 | new Promise((resolve, reject) => { |
cf9aa6c3 |
59 | externalPool.acquire( |
60 | './externalWorker.js', |
61 | { workerData: workerData }, |
62 | (err, worker) => { |
63 | if (err) { |
64 | return reject(err) |
65 | } |
66 | worker.on('error', reject) |
67 | worker.on('message', res => { |
68 | executions++ |
69 | resolve(res) |
70 | }) |
75b44e22 |
71 | } |
cf9aa6c3 |
72 | ) |
8d9ce260 |
73 | }).then(res => { |
cf9aa6c3 |
74 | if (tasks === executions) { |
75 | console.log( |
76 | `External pool take ${Date.now() - |
77 | time} to work on ${executions} tasks` |
78 | ) |
79 | } |
75b44e22 |
80 | }) |
81 | } |
75b44e22 |
82 | } |
83 | |
84 | async function test () { |
8d9ce260 |
85 | fixedTest() |
86 | dynamicTest() |
87 | externalPoolTest() |
75b44e22 |
88 | } |
89 | |
90 | test() |