3

I have an Express API app like this.

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');
});

I'm wondering what is the most accurate way to measure the response time ?

Babr
  • 1,971
  • 14
  • 33
  • 47

5 Answers5

8

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'
});

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.

Community
  • 1
  • 1
Horia Coman
  • 8,681
  • 2
  • 23
  • 25
  • What exactly do you mean? Seems like the question you're asking is more like "how to measure the time in my particular code?" rather than looking for accuracy or anything more special. – Horia Coman Dec 22 '18 at 16:31
  • This may help you : https://stackoverflow.com/a/64906447/3904109 – DragonFire Nov 19 '20 at 06:29
1

The issue is you are not doing any calculations to check how long it took you to response. Basically you will respond immediately. The right way of doing it if you have something to calculate would be something like this.

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');
});

You need to know what do you want to do. You can not just measure a request time because request time depends on how long you will take to do your calculations and so if you don't have calculations then there is nothing to take difference of. So with doWork I simulated a function that will sleep for 10 seconds. Instead of sleeping you might want to be querying from db or do some heavy math, etc...

Muhand Jumah
  • 1,726
  • 1
  • 11
  • 26
1

This functionality is already provided by Express and explained in the reference.

Express uses debug package. Debugging can be enabled via DEBUG environment variable either globally:

process.env.DEBUG = '*';

Or for Express router :

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

Measured time for each operation is logged in console:

express:router query : /api +2ms

express:router expressInit : /api +1ms

Estus Flask
  • 206,104
  • 70
  • 425
  • 565
  • This line should present in the script, simple as that. – Estus Flask Dec 23 '18 at 18:31
  • Well I added `process.env.DEBUG = 'express:router*';` to my code but nothing extra is printed on the console. – Babr Dec 23 '18 at 18:41
  • 1
    Try to add it as the first line. You can also pass DEBUG as environment variable from shell. – Estus Flask Dec 23 '18 at 18:43
  • Well now I get things like `express:router expressInit : /api +0ms`. Apparently it is not accurate enough to calculate less than milliseconds. – Babr Dec 23 '18 at 18:45
  • Were there no `query`? I assume that full request is `query` plus `expressInit`. You didn't define 'accurately' in the question, but I'd say that rounded 0ms is nitpicking. This route really takes virtually no time. – Estus Flask Dec 23 '18 at 18:53
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/185692/discussion-between-babr-and-estus). – Babr Dec 23 '18 at 19:10
1

The best solution that I found (thanks to this great tutorial), is to use morgan:

npm install morgan

And then use it in my code like this:

const morgan = require('morgan');


app.use(morgan('dev'));
Babr
  • 1,971
  • 14
  • 33
  • 47
1

The best solution using only node js:

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

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

time of execution = t1 - t0 (in ms)

Jet
  • 11
  • 2