如何用回调来衡量javascript代码的执行时间 [英] How to measure execution time of javascript code with callbacks

查看:135
本文介绍了如何用回调来衡量javascript代码的执行时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一段javascript代码,我正在使用node.js解释器执行。

I have a piece of javascript code that I am executing using the node.js interpreter.

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

我想知道如何测量这些数据库插入操作所花费的时间。我可以在这段代码之前和之前计算Date值的差异,但由于代码的异步性质,这将是不正确的。

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.

推荐答案

使用Node.js console.time() console.timeEnd()

Use the Node.js console.time() and 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");}
};

这篇关于如何用回调来衡量javascript代码的执行时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆