1

I have some JavaScript that I'm trying to benchmark the time it takes to execute.

The problem with this is that the for loop completes quickly, meanwhile the execution of the Item.save() method is not yet complete.

Any suggestions how to time this that takes into account the full execution time within the contents of the loop?

Thank you!

var start = new Date().getTime();
var Item = new Item();
for (i = 0; i < 500; i++) {
  var item = {};
  item.name = 5;
  item.id = 10;
  item.set = [];
  Item.save(item, function (err, res) {
    console.log(res);
  });
}
var elapsed = new Date().getTime() - start; 
console.log(elapsed);

EDIT: This is on a nodejs server.

3 Answers 3

1

Just use Chrome's profiling tools. They give you total insight into exactly how much CPU time every function call on your page is taking up:

http://code.google.com/chrome/devtools/docs/cpu-profiling-files/two_profiles.png


For Node, you can try node-inspector's experimental profiler.

Sign up to request clarification or add additional context in comments.

4 Comments

Sorry, I should have added NodeJS server.
Thanks, this is working well - However, it still will end the profiler mark, before all the executions have been done.
Chrome's profiling tools are useful for relative performance, but running with the profiler on is overall significantly slower than running with the console closed.
0

The best way to handle this would be to modify the Item.save() function to take in the start time and then do your comparison at the very end. Or, implement a callback function (succes:) on Item.save().

Comments

0

The answer is simple: create a jsPerf test case. It allows running asynchronous or “deferred” tests.

Alternatively, you could use Benchmark.js and set up a deferred test case manually.

Don’t simply compare two new Date timestamps, as that only works for synchronous tests. (Also, this is not an accurate way of measuring things across all browsers and devices.)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.