Calculating time spent inside the loop in javascript
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开发者_如何学Go inside the innermost loop. How do I do in javascript ?
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?
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.")
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:
- Accuracy of JavaScript Time
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 });
If you're using Firebug you can do
console.time('someNameHere');
// Do things here
console.timeEnd('someNameHere');
精彩评论