如何使用回调衡量JavaScript代码的执行时间? [英] How do I measure the execution time of JavaScript code with callbacks?

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

问题描述

我有一段使用node.js解释器执行的JavaScript代码.

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

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

如何测量这些数据库插入操作所花费的时间?我可以计算这段代码前后的日期值之差,但是由于代码的异步特性,这将是不正确的.

How can I measure the time taken by these database 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天全站免登陆