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 ?
+4
A:
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?
KennyTM
2010-01-14 07:11:55
ok.ThanksI am not sorting numbers , 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.
sat
2010-01-14 07:15:55
It's worth keeping in mind that the Date object is not terribly accurate. John Resig wrote an article about this: http://ejohn.org/blog/accuracy-of-javascript-time/.
Steve Harrison
2010-01-14 07:20:27
@sat: The `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: https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Array/sort#Parameters for more information.
Steve Harrison
2010-01-14 07:22:07
+3
A:
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:
CMS
2010-01-14 07:15:28
+2
A:
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 });
David Hedlund
2010-01-14 07:20:50
So in the above piece of code , its comparing the text property of 2 objects ? What algo is used internally ? means will it compare each n every object or some better algo ?
sat
2010-01-14 07:35:05
@sat: For Firefox, merge sort. This is used instead of quick sort to ensure the sort order is stable. See https://bugzilla.mozilla.org/show_bug.cgi?id=224128.
KennyTM
2010-01-14 07:38:28
@David: `arr.sort(function(x,y) { return x.text > y.text ? 1 : x.text < y.text ? -1 : 0 });`.
KennyTM
2010-01-14 07:39:12
@Kenny Thanks for that great info.U get to learn lot of things with simple questions.
sat
2010-01-14 07:48:35