sat
sat

Reputation: 41076

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 inside the innermost loop. How do I do in javascript ?

Upvotes: 7

Views: 10527

Answers (5)

Lukas Liesis
Lukas Liesis

Reputation: 26403

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.")

Upvotes: 9

Mike Fielden
Mike Fielden

Reputation: 10153

If you're using Firebug you can do

console.time('someNameHere');
// Do things here
console.timeEnd('someNameHere');

Upvotes: 2

David Hedlund
David Hedlund

Reputation: 129792

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 });

Upvotes: 2

Christian C. Salvad&#243;
Christian C. Salvad&#243;

Reputation: 827276

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:

Upvotes: 5

kennytm
kennytm

Reputation: 523234

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?

Upvotes: 8

Related Questions