You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
(async()=>{const{ job, start, stop }=require("microjob");try{// start the worker poolconsole.time("microjob");awaitstart();// this function will be executed in another threadconstres=awaitjob(()=>{leti=0;constresult=[];constthreadCount=4;consttotalDataLength=2000000;for(i=0;i<threadCount;i++){// heavy CPU load ...constcrypto=require("crypto");constsha256=(s)=>crypto.createHash("sha256").update(s).digest();constshaArray=Array.from(Array(totalDataLength/threadCount)).map((num)=>sha256(String(num)));result.push(shaArray);}returnresult;});console.log(res);console.timeEnd("microjob");}catch(err){console.error(err);}finally{// shutdown worker poolawaitstop();}})();
Node.js native multi-thread version
5311.715ms
const{ Worker }=require("worker_threads");constpath=require("path");console.time('thread')letworkerPool=[];constthreadCount=4;consttotalDataLength=2000000;for(leti=0;i<threadCount;i++){constworkerInstance=newPromise((resolve,reject)=>{constworker=newWorker(path.resolve("./worker.js"));worker.on("message",({ data })=>{resolve(data);});worker.postMessage({arrayLength: totalDataLength/threadCount,});});workerPool.push(workerInstance);}Promise.all(workerPool).then((values)=>{console.log(values);console.timeEnd('thread')}).catch((err)=>{console.log(err);});
I updated your example code for microjob so that it actually creates 4 worker threads.
The speed difference results are mostly negligible.
Fixed
(async()=>{const{ job, start, stop }=require("microjob");try{// start the worker poolconsole.time("microjob");awaitstart();constthreadCount=4;constpromises=[]for(leti=0;i<threadCount;i++){// this function will be executed in another threadconstresprom=job(()=>{constresult=[];consttotalDataLength=2000000;// heavy CPU load ...constcrypto=require("crypto");constsha256=(s)=>crypto.createHash("sha256").update(s).digest();constshaArray=Array.from(Array(totalDataLength/threadCount)).map((num)=>sha256(String(num)));result.push(shaArray);returnresult;},{ctx: { threadCount }});promises.push(resprom)}varres=awaitPromise.all(promises)console.log(res);console.timeEnd("microjob");}catch(err){console.error(err);}finally{// shutdown worker poolawaitstop();}})();
microjob version:
15375.269ms
Node.js native multi-thread version
5311.715ms
The text was updated successfully, but these errors were encountered: