You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

index.js 1.2KB

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