Multiple Embedded Loops In Nodejs
I like to execute the following code...but as you can see - it will require 10 billion loops! So i was wondering - what you guys would suggest to make it spin faster? The reason wh
Solution 1:
Break the loops into smaller chunks and fork processes using the core cluster module, processing each smaller chunk in a fork. The forks will run on separate threads, better leveraging the CPU.
https://nodejs.org/api/cluster.html#cluster_how_it_works
UPDATE. OK, don't use Cluster. Use the threads module instead - it will be much easier. https://www.npmjs.com/package/threads ...
var cores = require('os').cpus().length;
varPool = require('threads').Pool;
var pool = newPool(cores);
var doSomeThing = pool.run(function(data,done){
var result = data.a * data.b * data.c * data.d * data.e * data.f;
done(result,data);
})
var a = 0.1;
var b = 0.1;
var c = 0.1;
var d = 0.1;
var e = 0.1;
var f = 0.1;
while(a <= 10) // 100 loops
{
while(b <= 10) // 100 loops
{
while(c <= 10) // 100 loops
{
while(d <= 10) // 100 loops
{
while(e <= 10) // 10 loops
{
while(f <= 10) // 10 loops
{
// Call at method which use all parameters and return the result of a given calculation
doSomeThing.send({a:a,b:b,c:c,d:d,e:e,f:f});
f += 0.1;
}
e += 0.1;
}
d += 0.1;
}
c += 0.1;
}
b += 1;
}
a += 1;
}
pool
.on('error', function(job, error) {
console.error('Job errored:', job);
})
.on('finished', function() {
console.log('Everything done, shutting down the thread pool.');
pool.killAll();
});
Post a Comment for "Multiple Embedded Loops In Nodejs"