Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 890
Stormshadow Avatar asked May 16 '12 10:05

Stormshadow


People also ask

How do you find the execution time?

Calculate the execution time The difference between the end time and start time is the execution time. Get the execution time by subtracting the start time from the end time.

How many callback functions can be executed at any time?

As long as the callback code is purely sync than no two functions can execute parallel.


1 Answers

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");} }; 
like image 189
user2362662 Avatar answered Sep 28 '22 06:09

user2362662