How to check the number of seconds(or ms) spent inside the particular loop in javascript. I have a sorting algo implemented in javascript , now I am using bubble sort , I want to use quick sort. I know in terms of time efficiency Quick sort is good. But I want to calculate the real number of sec or milli sec spent inside the innermost loop. How do I do in javascript ?
5 Answers
All other answers in this thread are old.
Use this now, it's 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.")
Comments
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() (https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Array/sort) method?
4 Comments
sort method allows you to specify a compareFunction, which allows you to do exactly what you're after (without having to go off and create your own sorting method). See: developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/… for more information.Time is not really accurate on most browsers, you can expect a margin of error about of 15ms:
var start = (new Date).getTime();
/* Your code. */
var diff = (new Date).getTime() - start;
Recommended read:
1 Comment
Others have already answered how to do the time calculation, so I'll reply to your comment: "I am sorting array of objects where I sort depending on one of the property of the object. so built-in sort I cannot use."
That's not true at all, you can still use the built in sort:
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 });
4 Comments
arr.sort(function(x,y) { return x.text > y.text ? 1 : x.text < y.text ? -1 : 0 });.