-
Notifications
You must be signed in to change notification settings - Fork 0
/
run-workers.mjs
91 lines (71 loc) · 2.17 KB
/
run-workers.mjs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
import * as wt from 'node:worker_threads'
import * as url from 'node:url'
import { performance } from 'node:perf_hooks'
import {
benchmarkIterations,
processIterations,
workerPoolSize,
filesCount,
filesChunkSize,
dataURL,
processorURL,
} from '../config.mjs'
import {
chunkFiles,
getElapsedTime,
getAverageElapsedTime,
} from '../shared/utils.mjs'
const workerPath = url.fileURLToPath(new URL('./worker.mjs', import.meta.url))
const processorPath = url.fileURLToPath(processorURL)
const dataPath = url.fileURLToPath(dataURL)
const files = Array.from({ length: filesCount }, () => dataPath)
const chunkedFiles = chunkFiles(files, filesChunkSize)
async function run() {
let chunk = 0
const next = () => chunkedFiles[chunk++] ?? null
const workers = []
for (let i = 0; i < workerPoolSize; i++) {
workers.push(new wt.Worker(workerPath))
}
await Promise.all(
workers.map(
(worker) =>
new Promise((resolve, reject) => {
worker.postMessage({
action: 'load',
processorPath,
processIterations,
})
worker.on('error', reject)
worker.on('message', (message) => {
// message.action | message.results
// console.log('message.results:', message.results)
const filePaths = next()
if (filePaths) {
worker.postMessage({ action: 'process', filePaths })
} else {
worker.unref()
resolve('Processed files')
}
})
}),
),
)
}
console.log(
`node:worker_threads benchmark: Processing ${filesCount} files with ${workerPoolSize} workers\n`,
)
const runTimes = []
const benchmarkStartTime = performance.now()
for (let i = 0; i < benchmarkIterations; i++) {
const runStartTime = performance.now()
await run()
runTimes.push([runStartTime, performance.now()])
}
const benchmarkElapsedTime = getElapsedTime([
benchmarkStartTime,
performance.now(),
])
const averageElapsedTime = getAverageElapsedTime(runTimes)
console.log(`Average time to process ${filesCount} files: `, averageElapsedTime)
console.log('Benchmark elapsed time: ', benchmarkElapsedTime, '\n\n')