Skip to content

Instantly share code, notes, and snippets.

@renventura
Created May 20, 2025 03:58
Show Gist options
  • Save renventura/10c27adf28f7383ef596f07f17526e0a to your computer and use it in GitHub Desktop.
Save renventura/10c27adf28f7383ef596f07f17526e0a to your computer and use it in GitHub Desktop.
const { Worker, isMainThread, parentPort, workerData } = require("worker_threads");
const os = require("os");
console.time("Node Loop Benchmark");
const numThreads = os.cpus().length;
const total = 1_000_000_000;
const chunk = Math.floor(total / numThreads);
let completed = 0;
let sum = 0;
const sumTo = (n) => (n * (n - 1)) / 2;
if (isMainThread) {
return new Promise((resolve) => {
function handleMessage(partialSum) {
sum += partialSum;
completed++;
if (completed === numThreads) {
resolve();
}
}
for (let i = 0; i < numThreads; i++) {
const start = i * chunk;
const end = i === numThreads - 1 ? total : start + chunk;
const worker = new Worker(__filename, { workerData: { start, end } });
worker.on("message", handleMessage);
}
}).then(() => {
console.timeEnd("Node Loop Benchmark");
console.log("Sum:", sum);
});
} else {
const { start, end } = workerData;
const partialSum = sumTo(end) - sumTo(start);
parentPort.postMessage(partialSum);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment