-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathparallel.js
executable file
·44 lines (37 loc) · 1.35 KB
/
parallel.js
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
#!/usr/bin/node
/**
* This example shows that many PSO instances can be run in parallel.
*/
const cluster = require('cluster');
const numCPUs = require('os').cpus().length;
// main thread dispatches
if (cluster.isMaster) {
for (let i = 0; i < numCPUs; i++) {
console.log(`worker #${i} started`);
cluster.fork();
}
process.exit(0);
}
// this is the worker code
const PSO = require('..');
const SEC = 1000;
const f = xs => xs.reduce((x, y) => x + y, 0);
const nDims = 1500;
// randomness will ensure different config for every worker
const opts = {
nNeighs: 0.1 + (Math.random() * 0.3),
nParts: 30 + Math.floor(Math.random() * 70),
timeOutMS: 45 * SEC,
};
const pso = new PSO(f, nDims, opts);
// [optional] use the EventEmitter API for profiling
pso.on('start', (time, opts) => console.log(`[START] at ${new Date(time).toTimeString()} with opts`, opts));
pso.on('stuck', () => console.log(`[END] stuck`));
pso.on('timeout', () => console.log(`[END] timeout`));
pso.on('end', (nr, ms) => console.log(`[END] after round #${nr} (took ${ms / SEC}sec)`));
/* pso.search() will create a generator that iterates over the best population
* if you want the best solution, just request the very first: */
const best = pso.search().next().value;
const bestPossible = 1E9 * nDims;
const bestActual = f(best);
console.log('score', bestActual / bestPossible, '/ 1.0');