如何用回调来衡量javascript代码的执行时间

本文翻译自:How to measure execution time of javascript code with callbacks

I have a piece of javascript code that I am executing using the node.js interpreter. 我有一段javascript代码,我正在使用node.js解释器执行。

for(var i = 1; i < LIMIT; i++){
    db.users.save({id : i, name : "MongoUser [" + i + "]"}, function(err, saved) {
          if( err || !saved ) console.log("Error");
          else console.log("Saved");
    });
}

I want to know how to measure the time taken by these db insert operations. 我想知道如何测量这些数据库插入操作所花费的时间。 I could compute the difference of Date values after and before this piece of code but that would be incorrect because of the asynchronous nature of the code. 我可以计算这段代码之前和之前的Date值的差异,但由于代码的异步性质,这将是不正确的。


#1楼

参考:https://stackoom.com/question/IxZ4/如何用回调来衡量javascript代码的执行时间


#2楼

You could give Benchmark.js a try. 您可以试试Benchmark.js 。 It supports many platforms among them also node.js. 它支持其中的许多平台node.js.


#3楼

var start = +new Date();
var counter = 0;
for(var i = 1; i < LIMIT; i++){
    ++counter;
    db.users.save({id : i, name : "MongoUser [" + i + "]"}, function(err, saved) {
          if( err || !saved ) console.log("Error");
          else console.log("Saved");
          if (--counter === 0) 
          {
              var end = +new Date();
              console.log("all users saved in " + (end-start) + " milliseconds");
          }
    });
}

#4楼

There is a method that is designed for this. 有一种专门为此而设计的方法。 Check out process.hrtime(); 查看process.hrtime(); .

So, I basically put this at the top of my app. 所以,我基本上把它放在我的应用程序的顶部。

var start = process.hrtime();

var elapsed_time = function(note){
    var precision = 3; // 3 decimal places
    var elapsed = process.hrtime(start)[1] / 1000000; // divide by a million to get nano to milli
    console.log(process.hrtime(start)[0] + " s, " + elapsed.toFixed(precision) + " ms - " + note); // print message + time
    start = process.hrtime(); // reset the timer
}

Then I use it to see how long functions take. 然后我用它来看看函数需要多长时间。 Here's a basic example that prints the contents of a text file called "output.txt": 这是打印名为“output.txt”的文本文件内容的基本示例:

var debug = true;
http.createServer(function(request, response) {

    if(debug) console.log("----------------------------------");
    if(debug) elapsed_time("recieved request");

    var send_html = function(err, contents) {
        if(debug) elapsed_time("start send_html()");
        response.writeHead(200, {'Content-Type': 'text/html' } );
        response.end(contents);
        if(debug) elapsed_time("end send_html()");
    }

    if(debug) elapsed_time("start readFile()");
    fs.readFile('output.txt', send_html);
    if(debug) elapsed_time("end readFile()");

}).listen(8080);

Here's a quick test you can run in a terminal (BASH shell): 这是一个可以在终端(BASH shell)中运行的快速测试:

for i in {1..100}; do echo $i; curl http://localhost:8080/; done

#5楼

Use the Node.js console.time() and console.timeEnd() : 使用Node.js console.time()console.timeEnd()

var i;
console.time("dbsave");

for(i = 1; i < LIMIT; i++){
    db.users.save({id : i, name : "MongoUser [" + i + "]"}, end);
}

end = function(err, saved) {
    console.log(( err || !saved )?"Error":"Saved");
    if(--i === 1){console.timeEnd("dbsave");}
};

#6楼

Invoking console.time('label') will record the current time in milliseconds, then later calling console.timeEnd('label') will display the duration from that point. 调用console.time('label')将以毫秒为单位记录当前时间,然后调用console.timeEnd('label')将显示该点的持续时间。

The time in milliseconds will be automatically printed alongside the label, so you don't have to make a separate call to console.log to print a label: 以毫秒为单位的时间将自动与标签一起打印,因此您无需单独调用console.log来打印标签:

console.time('test');
//some code
console.timeEnd('test'); //Prints something like that-> test: 11374.004ms

For more information, see Mozilla's developer docs on console.time . 有关更多信息,请参阅有关console.time Mozilla开发人员文档 。

你可能感兴趣的:(javascript,node.js,profiling)