• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1'use strict'
2
3const CHILDREN         = 500
4    , POINTS_PER_CHILD = 1000000
5    , FARM_OPTIONS     = {
6          maxConcurrentWorkers        : require('os').cpus().length
7        , maxCallsPerWorker           : Infinity
8        , maxConcurrentCallsPerWorker : 1
9      }
10
11let workerFarm = require('../../')
12  , calcDirect = require('./calc')
13  , calcWorker = workerFarm(FARM_OPTIONS, require.resolve('./calc'))
14
15  , ret
16  , start
17
18  , tally = function (finish, err, avg) {
19      ret.push(avg)
20      if (ret.length == CHILDREN) {
21        let pi  = ret.reduce(function (a, b) { return a + b }) / ret.length
22          , end = +new Date()
23        console.log('π ≈', pi, '\t(' + Math.abs(pi - Math.PI), 'away from actual!)')
24        console.log('took', end - start, 'milliseconds')
25        if (finish)
26          finish()
27      }
28    }
29
30  , calc = function (method, callback) {
31      ret   = []
32      start = +new Date()
33      for (let i = 0; i < CHILDREN; i++)
34        method(POINTS_PER_CHILD, tally.bind(null, callback))
35    }
36
37console.log('Doing it the slow (single-process) way...')
38calc(calcDirect, function () {
39  console.log('Doing it the fast (multi-process) way...')
40  calc(calcWorker, process.exit)
41})
42