在node.js http请求上测量时间

我想知道是否可以使用node.js来测量完成http请求的时间。 从文档( 这里 )略微修改一个例子,可以很容易地写下下面的代码。

var http = require('http'); var stamp1 = new Date(); var stamp2, stamp3, stamp4; var options = { hostname: 'www.google.com', port: 80, path: '/upload', method: 'POST' }; var req = http.request(options, function(res) { stamp3 = new Date(); console.log('STATUS: ' + res.statusCode); console.log('HEADERS: ' + JSON.stringify(res.headers)); res.setEncoding('utf8'); res.on('data', function (chunk) { console.log('BODY: ' + chunk); }); res.on('end', function () { stamp4 = new Date(); console.log ("Stamp 3: " + stamp3); console.log ("Stamp 4: " + stamp4); }); }); req.on('error', function(e) { console.log('problem with request: ' + e.message); }); // write data to request body req.write('data\n'); req.write('data\n'); req.end(); stamp2 = new Date(); console.log ("Stamp 1: " + stamp1); console.log ("Stamp 2: " + stamp2); 

现在让我来谈谈我的观点。 在响应上,人们可以很容易地测量响应所花费的时间,因为在开始时设置了邮票3并且在结束邮戳4上设置了。 所以,原则上对于相对大量的数据,这两个时间戳将是不同的。

不过,我的问题是,邮票1和邮票2实际上是否在准备和派发请求时,衡量正在发生的事情。 换句话说,req.write(….)是一个同步操作吗? 基于node.js的原则,我期望req.write(…)是一个asynchronous操作,可以传递一个任意大的文档,然后成功完成后,我们可以知道请求已经完成。

注释?

两个function已经存在:

  • console.time(id),启动计时器
  • console.timeEnd(id)结束计时器,打印标识后面跟着时间,以毫秒为单位

所以在你的情况下:

 var req = http.request(options, function(res) { console.time('Requete: '); //Begin to count the time stamp3 = new Date(); console.log('STATUS: ' + res.statusCode); console.log('HEADERS: ' + JSON.stringify(res.headers)); res.setEncoding('utf8'); res.on('data', function (chunk) { console.log('BODY: ' + chunk); }); res.on('end', function () { stamp4 = new Date(); console.log ("Stamp 3: " + stamp3); console.log ("Stamp 4: " + stamp4); console.timeEnd('Requete: '); //Will print "Requete: X" with X being the time in ms }); }); 

文档提到没有callback,所以我假设req.write以及res.end同步。

所以在你的情况下,如果你指的是你正在初始化的一个请求,我认为时间测量应该是准确的。 我不认为时间差异很大(甚至在相同的毫秒)。