binary-trees Node js program
source code
/* The Computer Language Benchmarks Game
* https://salsa.debian.org/benchmarksgame-team/benchmarksgame/
*
* contributed by François Pirsch
* Based on the node.js program from Léo Sarrazin and Andrey Filatkin
*/
const { Worker, isMainThread, parentPort, workerData } = require('worker_threads');
if (isMainThread) {
mainThread();
} else {
workerThread();
}
async function mainThread () {
const maxDepth = Math.max(6, +process.argv[2] || 0);
const stretchDepth = maxDepth + 1;
const tasks = [{ iterations: 1, depth: stretchDepth }];
const longLivedTree = createTree(maxDepth);
for (let depth = 4; depth <= maxDepth; depth += 2) {
const iterations = 1 << maxDepth - depth + 4;
tasks.push({ iterations, depth });
}
(await runTasks(tasks)).forEach(result => process.stdout.write(result));
process.stdout.write(
`long lived tree of depth ${maxDepth}\t check: ${checksum(longLivedTree)}\n`
);
}
function runTasks (tasks) {
return new Promise(resolve => {
const results = [];
let tasksRemaining = tasks.length;
for (let i = 0; i < tasks.length; i++) {
new Worker(__filename, { workerData: tasks[i] })
.on('message', message => {
results[i] = message;
tasksRemaining--;
if (tasksRemaining === 0) {
resolve(results);
}
});
}
});
}
function workerThread () {
const { iterations, depth } = workerData;
let check = 0;
for (let i = 0; i < iterations; i++) {
check += checksum(createTree(depth));
}
parentPort.postMessage(
iterations === 1
? `stretch tree of depth ${depth}\t check: ${check}\n`
: `${iterations}\t trees of depth ${depth}\t check: ${check}\n`
);
}
function checksum (node) {
if (!node.left) {
return 1;
}
return 1 + checksum(node.left) + checksum(node.right);
}
function createTree (depth) {
return depth-- > 0
? { left: createTree(depth), right: createTree(depth) }
: { left: null, right: null };
}
notes, command-line, and program output
NOTES:
64-bit Ubuntu quad core
v14.2.0
Thu, 07 May 2020 01:38:10 GMT
MAKE:
cp -L binarytrees.node binarytrees.js
0.15s to complete and log all make actions
COMMAND LINE:
/opt/src/node-v14.2.0-linux-x64/bin/node binarytrees.js 21
PROGRAM OUTPUT:
stretch tree of depth 22 check: 8388607
2097152 trees of depth 4 check: 65011712
524288 trees of depth 6 check: 66584576
131072 trees of depth 8 check: 66977792
32768 trees of depth 10 check: 67076096
8192 trees of depth 12 check: 67100672
2048 trees of depth 14 check: 67106816
512 trees of depth 16 check: 67108352
128 trees of depth 18 check: 67108736
32 trees of depth 20 check: 67108832
long lived tree of depth 21 check: 4194303