1

I want to make the code bellow to calculate the time it takes to run the loop, but somehow none of the things I have tried worked!

I have tried using date, but it provides really inaccurate timing.

I have tried using another interval to check if an element already exists, and some similar solutions, etc, but the result is always the same, Javascript always checks things before the loop finishes!

var t = 0;

function myStartFunction() {

  myVar = setInterval(function() {
    t++;
    document.getElementById("tempo").innerHTML = "Elapsed time: " + t + " segundos";
  }, 1000);
}

myStartFunction();
function myStopFunction() {
  clearInterval(myVar);
}
var n = "";
var i = 0;
while (i < 100000) {
  n += "<br>" + i;
  i++;
  if (i == 100000) {
    ///////////////////clearInterval(myVar);
  }
}
document.getElementById("range").innerHTML = n;
<!DOCTYPE html>
<html>

<body>
  <h2 style="font-family:arial">TIME TO RUN LOOP</h2>
  <hr> <br>
  <button onclick="myStopFunction()">STOP</button> <br>

  <p id="tempo" style='font-family:arial'>Elapsed time: 0 segundos</p>
  <p id="range" style='font-family:arial'></p>

</body>

</html>

The best answer would be one that would provide an elapsed time in the following format: 00:00:00:0000

... without the need of a button!

And with a working clearInterval(myVar); where currently there is a Javascript comment.

Shankar
  • 2,890
  • 3
  • 25
  • 40
Fábio Linhares
  • 345
  • 5
  • 11
  • 1
    check this out https://stackoverflow.com/a/1975103/597384 – TommyBs Nov 01 '19 at 15:11
  • I would prefer a solution not involving node.js – Fábio Linhares Nov 01 '19 at 15:13
  • Something like this might be useful: https://medium.com/@olinations/an-accurate-vanilla-js-stopwatch-script-56ceb5c6f45b – calebkm Nov 01 '19 at 15:13
  • 1
    @FábioLinhares The solution that Tommy linked does not require Node.js, it just includes separate instructions if you *are* using Node. – Tyler Roper Nov 01 '19 at 15:14
  • It doesn't require nodeJS, it just says if you want to use it with NodeJS code you need to import performance. You can test it out right now in your developer console and see you don't need to use NodeJS – TommyBs Nov 01 '19 at 15:14
  • 1
    Do not attempt to measure the processing time of small snippets with some weird timer, with the goal of optimizing or understanding performance. You will end up in the corner, where all the people writing bogus stories about their newest sterile microbenchmark are. It's not productive. The measured times depend on too many other factors, and are in a lot of cases misleading and/or completely non-applicable in real world scenarios. – ASDFGerte Nov 01 '19 at 15:18

3 Answers3

2

use performance (see MDN). Or check this jsFiddle

let t = 0;
let start = performance.now();
let padZero = (v, n = 2) => `${v}`.padStart(n, "0");
let toTime = v => 
  `elapsed (hh:mm:ss:ms) ${
    padZero(Math.floor(v/(60*60000)))}:${
      padZero(Math.floor(v/60000))}:${
        padZero(Math.floor(v/1000))}:${
          padZero(Math.floor(v%1000), 3)}`;


myStartFunction();

function myStartFunction() {
  if (performance.now() > 10000) { 
    return console.log(`${toTime(performance.now() - start)} END`);
  }
  console.log(toTime(performance.now() - start));
  setTimeout(myStartFunction, 1000);
}
.as-console-wrapper { top: 0; max-height: 100% !important; }
KooiInc
  • 119,216
  • 31
  • 141
  • 177
1

Updated: I made this in the correct format with KooiInc code and changed out Date.Time for performance.now().

I changed your code a bit, this should calculate the time correctly for your while loop. Comment out the rest of your JavaScript code and put this code in your script.

I don't understand what you need for the ClearIntervalFunction exactly, but I can help you create that function if you give me more details on what you need.

function loop() {
  let n = "";
  let i = 0;

   while (i < 100000)
   {

    n += "<br>" + i;
    i++;

  }
  return n;
}

  function segundoFormatter(segundo) {
     let zeros = 8;
     let segundoArray = segundo.toString().split(".");
     let number2Add = zeros - segundoArray[0].length;
     let STR = "";
       for(let i = 0; i < number2Add; i++){
           STR += "0";
           if(i == 1 || i == 3 || i == 5){
               STR += ":";
           }
       }
       let finalStr = STR + segundoArray[0] + segundoArray[1];
       return finalStr.toString().substring(0,13);
     }



    window.onload = function(){
        let startTime = performance.now() 
        let n = loop();
        let endTime = performance.now() 
        let timeLoopTakes = (endTime - startTime);//00:00:00:0000
       // segundoFormatter(timeLoopTakes);
        document.getElementById("tempo").innerHTML = "Elapsed time: " + 
        segundoFormatter(timeLoopTakes) + " segundos";
      //You can uncomment this line belowand get like 10000 things in your dom
     //document.getElementById("range").innerHTML = n;
 }
nuccio
  • 316
  • 6
  • 17
  • If I uncomment this line on your code nothing shows up `document.getElementById("range").innerHTML = n;` – Fábio Linhares Nov 01 '19 at 16:33
  • `clearInterval(myVar);` was used to stop calculating the time manually, but the intention is to stop it automatically like your code is doing. – Fábio Linhares Nov 01 '19 at 16:37
  • Your code does not generate what's inside the loop. It's also not calculating the time correctly. Although, It has the proper timing format, which is like I want. – Fábio Linhares Nov 01 '19 at 16:42
  • Do you really want to show 100000 actual elements in your page? I took it out on purpose. But I can help you put it back. – nuccio Nov 01 '19 at 17:09
  • I am going to reformat my code with ideas from KooiInc. – nuccio Nov 01 '19 at 17:09
0

You can use the getTime() function of the Date object to get the UNIX timestamp associated with the current time.

let initialTime = new Date().getTime();

for(let i = 0; i < 100000000; i ++) {
  // do something
}
let finalTime = new Date().getTime();
console.log ('this took : ' +  (finalTime - initialTime) + ' milliseconds' );
Nicolas
  • 8,077
  • 4
  • 21
  • 51