Calculating time spent inside a loop in javascript

How to check the number of seconds (or ms) spent inside a particular loop in javascript. I have algo sorting implemented in javascript, now I am using bubble sorting, I want to use quick sorting. I know in terms of time efficiency. Quick sorting is good. But I want to calculate the actual number of seconds or milliseconds spent inside the innermost loop. How do I do in javascript?

+6
performance javascript
source share
5 answers

The simplest method is to compare by date.

var old_time = new Date(); ... var new_time = new Date(); var seconds_passed = new_time - old_time; 
By the way, why don't you just use the built-in .sort() method ( https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Array/sort )?
+7
source share

In most browsers, the time is not very accurate, you can expect an error of about 15 ms:

 var start = (new Date).getTime(); /* Your code. */ var diff = (new Date).getTime() - start; 

Recommended reading:

+4
source share

Others have already answered how to calculate the time, so I will answer your comment: "I sort the array of objects in which I sort, depending on one of the properties of the object, so I cannot use the built-in sorting."

This is not entirely true, you can still use the built-in view:

 var arr = [{ text: 'test', id: 2 }, { text: 'abc', id: 6 }, { text: 'xyz', id: 4 }]; arr.sort(function(x,y) { return x.text > y.text ? 1 : x.text < y.text ? -1 : 0 }); 
+2
source share

If you use Firebug, you can do

 console.time('someNameHere'); // Do things here console.timeEnd('someNameHere'); 
+1
source share

All other answers in this thread are old.

Use it now, it is standard https://developer.mozilla.org/en-US/docs/Web/API/Performance.now

 var t0 = performance.now(); doSomething(); var t1 = performance.now(); console.log("Call to doSomething took " + (t1 - t0) + " milliseconds.") 
+1
source share

All Articles