Skip to content
Snippets Groups Projects
Select Git revision
  • 499a5c5559c7d48a6896eccd1da75f9c10bff9cb
  • master default protected
2 results

index.html

Blame
  • clusterpi.js 1.45 KiB
    //
    // clusterpi.js
    // Neil Gershenfeld 11/23/18
    // pi calculation benchmark
    // pi = 3.14159265358979323846
    //
    const cluster = require('cluster')
    const points = 1e8
    if (cluster.isMaster) 
       master()
    else
       child()
    function master() {
       var processes = require('os').cpus().length
       var tstart = Date.now()/1000
       for (var i = 0; i < processes; i++)
          cluster.fork()
       var index = 0
       var pi = 0
       var results = 0
       for (const id in cluster.workers) {
          var worker = cluster.workers[id]
          worker.on('message',(result) => {
             pi += result
             results += 1
             if (results == processes) {
                var tend = Date.now()/1000
                var mflops = (processes*points)*5.0*1e-6/(tend-tstart)
                console.log('pi: '+pi)
                console.log('time: '+(tend-tstart).toFixed(1)+'s')
                console.log('processes: '+processes)
                console.log('estimated MFlops: '+mflops.toFixed(1))
                process.exit()
                }
             })
          function send(index) {
             return function() {
                worker.send(index)
                }
             }
          worker.on('online',send(index))
          index += 1
          }
       }
    function child() { 
       process.on('message',(index) => {
          var a = 0.5
          var b = 0.75
          var c = 0.25
          var sum = 0
          var start = 1+points*index
          var end = points*(index+1)
          for (var i = start; i <= end; ++i)
             sum += a/((i-b)*(i-c))
          process.send(sum)
          })
       }