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

Bab*_*abr 1 response node.js express

我有一个这样的 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');
});
Run Code Online (Sandbox Code Playgroud)

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

Hor*_*man 5

You might also want to use the Performance timing API in Node (and browsers) to use an API meant explicitly for measuring performance, rather than relying on Date. Besides the more semantic API, you can have better resolution, and the API will deal with issues like a "later" call to Date returning a value lower than an "earlier" call because someones messed with the system time.

The docs are pretty self-explanatory:

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'
});
Run Code Online (Sandbox Code Playgroud)

OTOH, with regards to performance measurement, and especially latency/duration measurements, it's all in the eyes of the measurer. The most accurate way to do it is to measure in the client code and take into account things like network latency, intermediate processing, framework delays, etc.