Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 364
sat Avatar asked Jan 14 '10 07:01

sat


People also ask

How do you sum a loop in JavaScript?

The parseInt() converts the numeric string value to an integer value. The for loop is used to find the sum of natural numbers up to the number provided by the user. The value of sum is 0 initially. Then, a for loop is used to iterate from i = 1 to 100 .

How does JavaScript calculate start and end time?

var start = new Date(). getTime(); for (i = 0; i < 50000; ++i) { // do something } var end = new Date(). getTime(); var time = end - start; alert('Execution time: ' + time); One can solve the same problem using a variety of different strategies Javascript Calculate Time.

How do you code time in JavaScript?

Javascript Clock Code (12 hours): function currentTime() { let date = new Date(); let hh = date. getHours(); let mm = date. getMinutes(); let ss = date. getSeconds(); let session = "AM"; if(hh == 0){ hh = 12; } if(hh > 12){ hh = hh - 12; session = "PM"; } hh = (hh < 10) ?


1 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() (https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Array/sort) method?

like image 137
kennytm Avatar answered Sep 20 '22 13:09

kennytm