本页内容

    对 Node.js 应用进行性能分析,是指在应用运行时通过分析 CPU、内存及其他运行时指标来衡量其性能。这有助于识别可能影响应用效率、响应能力和可扩展性的瓶颈、高 CPU 占用、内存泄漏或缓慢的函数调用。

    有许多第三方工具可用于分析 Node.js 应用,但在很多情况下,最简单的选择是使用 Node.js 内置的性能分析器。内置分析器使用 V8 内置的性能分析器,在程序执行期间按固定间隔对堆栈采样。它将这些采样的结果以及 jit 编译等重要优化事件记录为一系列 tick:

    code-creation,LazyCompile,0,0x2d5000a337a0,396,"bp native array.js:1153:16",0x289f644df68,~
    code-creation,LazyCompile,0,0x2d5000a33940,716,"hasOwnProperty native v8natives.js:198:30",0x289f64438d0,~
    code-creation,LazyCompile,0,0x2d5000a33c20,284,"ToName native runtime.js:549:16",0x289f643bb28,~
    code-creation,Stub,2,0x2d5000a33d40,182,"DoubleToIStub"
    code-creation,Stub,2,0x2d5000a33e00,507,"NumberToStringStub"
    

    过去,你需要 V8 源代码才能解释这些 tick。幸运的是,从 Node.js 4.4.0 开始引入了一些工具,让你无需单独从源码构建 V8 也能方便地使用这些信息。让我们看看内置分析器如何帮助深入了解应用性能。

    为了演示 tick 分析器的使用,我们将使用一个简单的 Express 应用。我们的应用有两个处理函数,一个用于向系统添加新用户:

    app.get('/newUser', (req, res) => {
      let username = req.query.username || '';
      const password = req.query.password || '';
    
      username = username.replace(/[^a-zA-Z0-9]/g, '');
    
      if (!username || !password || users[username]) {
        return res.sendStatus(400);
      }
    
      const salt = crypto.randomBytes(128).toString('base64');
      const hash = crypto.pbkdf2Sync(password, salt, 10000, 512, 'sha512');
    
      users[username] = { salt, hash };
    
      res.sendStatus(200);
    });

    另一个用于验证用户认证尝试:

    app.get('/auth', (req, res) => {
      let username = req.query.username || '';
      const password = req.query.password || '';
    
      username = username.replace(/[^a-zA-Z0-9]/g, '');
    
      if (!username || !password || !users[username]) {
        return res.sendStatus(400);
      }
    
      const { salt, hash } = users[username];
      const encryptHash = crypto.pbkdf2Sync(password, salt, 10000, 512, 'sha512');
    
      if (crypto.timingSafeEqual(hash, encryptHash)) {
        res.sendStatus(200);
      } else {
        res.sendStatus(401);
      }
    });

    请注意,这些处理函数并不推荐用于在你的 Node.js 应用中认证用户,纯粹是为了演示而使用。一般来说,你不应该尝试自行设计加密认证机制。使用现有的、经过验证的认证方案要好得多。

    现在假设我们已经部署了应用,用户抱怨请求延迟很高。我们可以轻松使用内置分析器运行应用:

    NODE_ENV=production node --prof app.js
    

    并用 ab(ApacheBench)给服务器施加一些负载:

    curl -X GET "http://localhost:8080/newUser?username=matt&password=password"
    ab -k -c 20 -n 250 "http://localhost:8080/auth?username=matt&password=password"
    

    得到 ab 的输出如下:

    Concurrency Level:      20
    Time taken for tests:   46.932 seconds
    Complete requests:      250
    Failed requests:        0
    Keep-Alive requests:    250
    Total transferred:      50250 bytes
    HTML transferred:       500 bytes
    Requests per second:    5.33 [#/sec] (mean)
    Time per request:       3754.556 [ms] (mean)
    Time per request:       187.728 [ms] (mean, across all concurrent requests)
    Transfer rate:          1.05 [Kbytes/sec] received
    
    ...
    
    Percentage of the requests served within a certain time (ms)
      50%   3755
      66%   3804
      75%   3818
      80%   3825
      90%   3845
      95%   3858
      98%   3874
      99%   3875
     100%   4225 (longest request)
    

    从这个输出中可以看出,我们每秒只能处理约 5 个请求,平均每个请求的往返时间接近 4 秒。在真实场景中,我们可能会代表用户请求在许多函数中做大量工作,但即使在这个简单示例中,时间也可能消耗在编译正则表达式、生成随机盐、根据用户密码生成唯一散列,或 Express 框架本身内部。

    由于我们使用 --prof 选项运行应用,因此在本地运行应用的同一目录下生成了一个 tick 文件。其格式应为 isolate-0xnnnnnnnnnnnn-v8.log(其中 n 是数字)。

    为了理解这个文件,我们需要使用随 Node.js 二进制文件一起提供的 tick 处理器。要运行该处理器,使用 --prof-process 标志:

    node --prof-process isolate-0xnnnnnnnnnnnn-v8.log > processed.txt
    

    用你喜欢的文本编辑器打开 processed.txt,会看到几种不同类型的信息。文件按区段划分,区段内又按语言划分。首先,我们查看 summary 区段,看到:

     [Summary]:
       ticks  total  nonlib   name
         79    0.2%    0.2%  JavaScript
      36703   97.2%   99.2%  C++
          7    0.0%    0.0%  GC
        767    2.0%          Shared libraries
        215    0.6%          Unaccounted
    

    这告诉我们,收集到的所有样本中有 97% 发生在 C++ 代码中,因此在查看处理后输出的其他区段时,应最关注 C++ 中完成的工作(而非 JavaScript)。基于此,接下来我们找到 [C++] 区段,它包含哪些 C++ 函数占用最多 CPU 时间的信息,看到:

     [C++]:
       ticks  total  nonlib   name
      19557   51.8%   52.9%  node::crypto::PBKDF2(v8::FunctionCallbackInfo<v8::Value> const&)
       4510   11.9%   12.2%  _sha1_block_data_order
       3165    8.4%    8.6%  _malloc_zone_malloc
    

    我们看到前 3 项占程序 CPU 时间的 72.1%。从这个输出中,我们立即看出至少 51.8% 的 CPU 时间被一个名为 PBKDF2 的函数占用,它对应我们根据用户密码生成散列的操作。不过,下面两项如何影响我们的应用可能并不显而易见(即便显而易见,为了举例我们也会假装不知道)。为了更好地理解这些函数之间的关系,接下来查看 [Bottom up (heavy) profile] 区段,它提供每个函数主要调用方的信息。检查该区段,我们发现:

       ticks parent  name
      19557   51.8%  node::crypto::PBKDF2(v8::FunctionCallbackInfo<v8::Value> const&)
      19557  100.0%    v8::internal::Builtins::~Builtins()
      19557  100.0%      LazyCompile: ~pbkdf2 crypto.js:557:16
    
       4510   11.9%  _sha1_block_data_order
       4510  100.0%    LazyCompile: *pbkdf2 crypto.js:557:16
       4510  100.0%      LazyCompile: *exports.pbkdf2Sync crypto.js:552:30
    
       3165    8.4%  _malloc_zone_malloc
       3161   99.9%    LazyCompile: *pbkdf2 crypto.js:557:16
       3161  100.0%      LazyCompile: *exports.pbkdf2Sync crypto.js:552:30
    

    解析这一区段比上面的原始 tick 计数需要更多工作。在上面每个“调用栈”中,parent 列的百分比表示:在多少比例的样本中,上一行的函数被当前行的函数调用。例如,在上面关于 _sha1_block_data_order 的中间“调用栈”中,我们看到 _sha1_block_data_order 出现在 11.9% 的样本中,这从上面的原始计数中已经知道。不过,在这里我们还能看出它总是由 Node.js crypto 模块中的 pbkdf2 函数调用。同样,_malloc_zone_malloc 几乎也只由同一个 pbkdf2 函数调用。因此,利用这个视图中的信息,我们可以判断:根据用户密码计算散列不仅占上面提到的 51.8%,还占了采样最多的前 3 个函数中的全部 CPU 时间,因为对 _sha1_block_data_order 和 _malloc_zone_malloc 的调用都是代表 pbkdf2 函数发出的。

    此时,很明显,基于密码的散列生成应当成为我们优化的目标。值得庆幸的是,你已经完全理解了异步编程的好处,并意识到根据用户密码生成散列的工作是以同步方式完成的,从而拖住了事件循环。这使我们无法在计算散列的同时处理其他传入请求。

    为了解决这个问题,你对上面的处理函数稍作修改,使用 pbkdf2 函数的异步版本:

    app.get('/auth', (req, res) => {
      let username = req.query.username || '';
      const password = req.query.password || '';
    
      username = username.replace(/[^a-zA-Z0-9]/g, '');
    
      if (!username || !password || !users[username]) {
        return res.sendStatus(400);
      }
    
      crypto.pbkdf2(
        password,
        users[username].salt,
        10000,
        512,
        'sha512',
        (err, hash) => {
          if (users[username].hash.toString() === hash.toString()) {
            res.sendStatus(200);
          } else {
            res.sendStatus(401);
          }
        }
      );
    });

    使用异步版本的应用再次运行上面的 ab 基准测试,结果为:

    Concurrency Level:      20
    Time taken for tests:   12.846 seconds
    Complete requests:      250
    Failed requests:        0
    Keep-Alive requests:    250
    Total transferred:      50250 bytes
    HTML transferred:       500 bytes
    Requests per second:    19.46 [#/sec] (mean)
    Time per request:       1027.689 [ms] (mean)
    Time per request:       51.384 [ms] (mean, across all concurrent requests)
    Transfer rate:          3.82 [Kbytes/sec] received
    
    ...
    
    Percentage of the requests served within a certain time (ms)
      50%   1018
      66%   1035
      75%   1041
      80%   1043
      90%   1049
      95%   1063
      98%   1070
      99%   1071
     100%   1079 (longest request)
    

    太好了!你的应用现在每秒可以处理约 20 个请求,大约是使用同步散列生成时的 4 倍。此外,平均延迟从之前的 4 秒降到了略高于 1 秒。

    希望通过这个(不可否认有些刻意设计的)示例的性能调查,你已看到 V8 tick 处理器如何帮助你更好地理解 Node.js 应用的性能。

    你也许还会发现如何创建火焰图很有帮助。