Node.js群集比单线程模式慢

时间:2018-11-23 07:57:37

标签: node.js cluster-computing

我只是在Node.js中尝试集群。我写了一个fibonacci例子,在其中我使用集群服务器和非集群服务器调用函数,如下所示。

// fib.js

module.exports = function () {
    const store = []
    store[0] = 0
    store[1] = 1

    return function fib(n) {
        if (store[n] === undefined) {
            store[n] = fib(n - 2) + fib(n - 1)
        }

        return store[n]
    }
}

// non-clustered server

const http = require('http')
const fib = require('./fib.js')

const f = fib()
http.createServer((req, res) => {
    res.writeHead(200)
    res.end(`From ${process.pid}: ${f(30)}\n`)
}).listen(8000)

// clustered server

const cluster = require('cluster')
const http = require('http')
const numCPUs = require('os').cpus().length
const fib = require('./fib.js')

const f = fib()
if (cluster.isMaster) {
    for (let i = 0; i < numCPUs; i++) {
        cluster.fork()
    }
} else {
    http.createServer((req, res) => {
        res.writeHead(200)
        res.end(`From ${process.pid}: ${f(30)}\n`)
    }).listen(8000)
}

现在,我尝试使用artillery对这两个服务器的性能进行基准测试,但是非群集服务器似乎更快。怎么会来?

// Clustered Server Report

Started phase 0, duration: 1s @ 07:53:24(+0000) 2018-11-23
Report @ 07:53:27(+0000) 2018-11-23
  Scenarios launched:  50
  Scenarios completed: 50
  Requests completed:  2000
  RPS sent: 803.21
  Request latency:
    min: 0.3
    max: 70.5
    median: 20.7
    p95: 38.7
    p99: 45.6
  Codes:
    200: 2000

All virtual users finished
Summary report @ 07:53:27(+0000) 2018-11-23
  Scenarios launched:  50
  Scenarios completed: 50
  Requests completed:  2000
  RPS sent: 796.81
  Request latency:
    min: 0.3
    max: 70.5
    median: 20.7
    p95: 38.7
    p99: 45.6
  Scenario counts:
    0: 50 (100%)
  Codes:
    200: 2000

// Non-clustered Server Report

Started phase 0, duration: 1s @ 07:53:39(+0000) 2018-11-23
Report @ 07:53:41(+0000) 2018-11-23
  Scenarios launched:  50
  Scenarios completed: 50
  Requests completed:  2000
  RPS sent: 806.45
  Request latency:
    min: 0.3
    max: 70.1
    median: 21.4
    p95: 38.3
    p99: 44.6
  Codes:
    200: 2000

All virtual users finished
Summary report @ 07:53:41(+0000) 2018-11-23
  Scenarios launched:  50
  Scenarios completed: 50
  Requests completed:  2000
  RPS sent: 800
  Request latency:
    min: 0.3
    max: 70.1
    median: 21.4
    p95: 38.3
    p99: 44.6
  Scenario counts:
    0: 50 (100%)
  Codes:
    200: 2000