Search code examples
javascriptnode.jsprofiling

How do I measure the execution time of JavaScript code with callbacks?


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.


Solution

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