Properly Measuring HTTP Request Time With Node.js

综合技术 2018-03-13

When your backend code is calling external APIs, you may want to measure particular request time to identify bottlenecks.

The most straightforward, but incorrect, way to measure how long request takes is to use JavaScript Date
object:

var request = require('request');

let start_time = new Date().getTime();

request.get('https://google.com', function (err, response) {
    console.log('Time elapsed:', new Date().getTime() - start_time);
});

However, this won't give you the actual time that request takes. Above request call is async, and you start measuring time at the time when request was queued, not actually sent.

In order to determine how much time elapsed since sending request, you can use the time
parameter:

var request = require('request');

request.get({ url: 'http://www.google.com', time: true }, function (err, response) {
    console.log('The actual time elapsed:', response.elapsedTime);
});

You can also compare results returned by both methods:

var request = require('request');

let start_time = new Date().getTime();

request.get('https://google.com', function (err, response) {
    console.log('Time elapsed since queuing the request:', new Date().getTime() - start_time);
});

request.get({ url: 'http://www.google.com', time: true }, function (err, response) {
    console.log('The actual time elapsed:', response.elapsedTime);
});

When I run it, I got the following results:

The actual time elapsed: 72
Time elapsed since queuing the request: 156

Notice that the first callback resolves after the second one (!).

The difference is almost 2x. Depending on your server side code, this difference might be even larger, and give you incorrect hints while you are profiling your application.

DZone

责编内容来自:DZone (本文源链)。感谢您的支持!

您可能感兴趣的

如何收集捕获Node中的未处理的错误异常信息?... 因为我们的产品主要是以js栈为主,下面来讲一下我们实践。 e.stack 异常栈 node.js是出错异常了,最关键是要知道哪错了。stack是error很重要的一个属性,可以帮助我们了解代码...
HTTP request node.js using mikeal’s ‘r... I'm trying to use https://github.com/mikeal/request . What is wrong with my code? Error message ...
NodeJs之数据库异常处理 数据库异常 NodeJs版本:4.4.4 数据库链接错误 使用nodejs处理异常最麻烦不过,这里我抛开nodejs提供的 domain 和一些第三方库专门处理的东西。操作数据库是...
Node.js separate module dependencies What is the best way to separate all module dependencies into a new file called depen...
NodeJS takes forever to build on AWS EC2 I am trying to setup NodeJS on EC2. I followed the official guide and it was successful on my lo...