0

I don't know how to do this. Javascript is single-threaded, so I can't run function and timer at the same time. How to check how much time my function executes?

nicael
  • 18,550
  • 13
  • 57
  • 90

1 Answers1

0

You can use the getTime() method of the Date object.

var start = new Date().getTime();

for (var i = 0; i < 100000; ++i) {
    // work
}

var end = new Date().getTime();
var time = end - start;
console.log('Execution time: ' + time);

The start is the moment when your code starts executing. The end is the moment when it finishes execution. If you make the difference between those 2 moments you get the time it took for it to execute.

Also, taking into account the fact that in javascript you can pass functions as arguments, you can do something like this:

function profile(myCode) {
    var start = new Date().getTime(); //the moment when execution starts

    myCode(); //execute your code

    var end = new Date().getTime(); // the moment when execution finishes
    var time = end - start; // time it took
    console.log('Execution time: ' + time); // output the time to console
    return time; // return the time for further use
}
Andrei
  • 3,086
  • 2
  • 19
  • 24
  • Could you please explain the downvote so I can improve my answer? – Andrei Jun 11 '14 at 14:25
  • 1
    Probably I understand. My question was marked as dupe recently and you seem to have copied the accepted answer from original question. – nicael Jun 11 '14 at 14:27
  • I haven't copied any answer. Also, I don't see it marked as dupe. It could resemble other answers since it has only 3 lines of code. Oh well. – Andrei Jun 11 '14 at 14:30
  • "Also, I don't see it marked as dupe" - ?? – nicael Jun 11 '14 at 14:31
  • Where is your question marked as duplicate ? – Andrei Jun 11 '14 at 14:32
  • Hit F5. Or cmd-r if you are on Mac. – nicael Jun 11 '14 at 14:33
  • Ok, I see it now. Seems that this change was not pushed to my browser. Yeah, it does resemble that answer but I didn't copy it. It is just common practice. Also I have added more explanation than that answer. – Andrei Jun 11 '14 at 14:35
  • I already up voted you so I can't do it one more time. – nicael Jun 11 '14 at 14:36
  • Thank you! I just wanted to clarify a wrongful accusation. This answer was the only one in the last days so I don't care about rep anymore. – Andrei Jun 11 '14 at 14:40