在 node.js 中如何准确测量响应时间?

How accuratly measure response time in node.js?

我有一个这样的 Express API 应用程序。

var express = require('express');     
const app = express();    
app.get('/api', function(req, res) {
  res.json({
      text: 'my api!' 
  });
 )
});

app.listen(8090, function () {
    console.log('App listening on port 8090');
});

我想知道测量响应时间最准确的方法是什么?

问题是你没有做任何计算来检查你花了多长时间做出回应。基本上你会立即回应。如果你有一些东西要计算的话,正确的做法是这样的。

var express = require('express');     
const app = express();    
app.get('/api', function(req, res) {
  var start = new Date();

  doWork((err) => {
      var end = new Date() - start
      res.status = 200;
      res.end(`It took ${end}ms`);
  })
 )
});

function doWork(callback) {
    // Sleep for 10 seconds
    // This can be any logic, not only sleep (sleep in this case is use
    // to simulate a function that takes long to respond
    setTimeout(function(){callback(null)}, 10000);
}

app.listen(8090, function () {
    console.log('App listening on port 8090');
});

你需要知道你想做什么。您不能只测量请求时间,因为请求时间取决于您将花费多长时间进行计算,因此如果您没有计算,那么就没有什么可取的。因此,使用 doWork 我模拟了一个休眠 10 秒的函数。你可能不想睡觉,而是想从数据库查询或做一些繁重的数学运算,等等...

您可能还想在 Node(和浏览器)中使用 Performance timing API 来使用 API 明确用于测量性能,而不是依赖 Date. 除了更多的语义API,您可以获得更好的分辨率,并且 API 将处理诸如 "later" 调用 Date 返回的值低于 "earlier" 调用的问题,因为有人弄乱了系统时间。

这些文档非常不言自明:

const { performance } = require('perf_hooks');
performance.mark('A');
doSomeLongRunningProcess(() => {
    performance.mark('B');
    performance.measure('A to B', 'A', 'B');
    const measure = performance.getEntriesByName('A to B')[0];
    console.log(measure.duration);
    // Prints the number of milliseconds between Mark 'A' and Mark 'B'
});

OTOH,关于性能测量,尤其是 latency/duration 测量,一切都在测量者的眼中。最准确的方法是在客户端代码中进行测量,并考虑网络延迟、中间处理、框架延迟等因素。

此功能已由 Express 提供并在 the reference 中进行了解释。

快递使用debug包裹。可以通过 DEBUG 环境变量全局启用调试:

process.env.DEBUG = '*';

或者对于 Express 路由器:

process.env.DEBUG = 'express:router*';

每个操作的测量时间记录在控制台中:

express:router query : /api +2ms

express:router expressInit : /api +1ms

我找到的最佳解决方案(感谢 this great tutorial)是使用 morgan:

npm install morgan

然后像这样在我的代码中使用它:

const morgan = require('morgan');


app.use(morgan('dev'));

仅使用 node js 的最佳解决方案:

const { performance } = require("perf_hooks");

const t0 = performance.now();
// your code
const t1 = performance.now();

执行时间 = t1 - t0(毫秒)